-
Notifications
You must be signed in to change notification settings - Fork 4
/
stack.py
60 lines (48 loc) · 1.44 KB
/
stack.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
class Stack:
class EmptyStackError(Exception):
def __str__(self) -> str:
return "Stack is empty."
def __init__(self) -> None:
self._data: list[object] = []
self._size: int = 0
def __len__(self) -> int:
return self._size
def length(self) -> int:
return self.__len__()
def __str__(self) -> str:
return str(self._data)
def __eq__(self, other: 'Stack') -> bool:
if self.__class__ == other.__class__:
if self._data == other._data and self._size == other._size:
return True
return False
def is_empty(self) -> bool:
return self._size == 0
def top(self) -> object:
if self.is_empty():
raise Stack.EmptyStackError
return self._data[-1]
def push(self, element: object) -> None:
self._data.append(element)
self._size += 1
def pop(self) -> object:
if self.is_empty():
raise Stack.EmptyStackError
self._size -= 1
return self._data.pop()
def empty_stack(self) -> None:
while not self.is_empty():
self.pop()
if __name__ == '__main__':
stack = Stack()
print(stack.is_empty())
for i in range(10):
stack.push(i)
print(stack.top())
print(stack.pop())
print(stack)
print(len(stack))
print(stack.length())
print(stack.is_empty())
stack.empty_stack()
print(stack.is_empty())