-
Notifications
You must be signed in to change notification settings - Fork 7
/
9.py
87 lines (71 loc) · 2.13 KB
/
9.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import enum
import sys
from typing import (
List,
Optional,
Tuple,
NoReturn,
)
class MyQueueSized:
def __init__(self, max_size: int):
self.data: List[Optional[int]] = [None] * max_size
self.max_size = max_size
self.head = 0
self.tail = 0
self.size = 0
def is_empty(self):
return self.size == 0
def push(self, x: int):
if self.size == self.max_size:
raise AssertionError("Max size")
self.data[self.tail] = x
self.tail = (self.tail + 1) % self.max_size
self.size += 1
def pop(self) -> Optional[NoReturn]:
if self.is_empty():
return None
x = self.data[self.head]
self.data[self.head] = None
self.size -= 1
self.head = (self.head + 1) % self.max_size
return x
def peek(self):
return self.data[self.head]
def get_commands(command_length: int) -> List[Tuple[str, Optional[int]]]:
commands: List[Tuple[str, int]] = []
for _ in range(command_length):
data: List[str, Optional[str]] = (
sys.stdin.readline().rstrip().split(" ")
)
command: Tuple[str, Optional[int]] = (
data[0],
int(data[1]) if len(data) > 1 else None,
)
commands.append(command)
return commands
class CommandFuncName(enum.Enum):
peek = "peek"
push = "push"
pop = "pop"
size = "size"
def execute_command(stack: MyQueueSized, command: Tuple[str, Optional[int]]):
func = command[0]
number: Optional[int] = command[1]
if func == CommandFuncName.peek.value:
print(stack.peek())
elif func == CommandFuncName.push.value:
try:
stack.push(number)
except AssertionError:
print("error")
elif func == CommandFuncName.pop.value:
print(stack.pop())
elif func == CommandFuncName.size.value:
print(stack.size)
def main():
commands_length: int = int(input())
max_size: int = int(input())
stack = MyQueueSized(max_size=max_size)
for command in get_commands(commands_length):
execute_command(stack, command)
main()