-
Notifications
You must be signed in to change notification settings - Fork 0
/
dynamic_stack.py
52 lines (41 loc) · 1003 Bytes
/
dynamic_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
class Stack:
def __init__(self) -> None:
self.data = []
self.top = -1
def is_empty(self):
return self.top == -1
def push(self, elem):
if len(self.data) == self.top + 1:
self.data.append(elem)
else:
self.data[self.top] = elem
self.top += 1
def pop(self):
if self.is_empty():
raise StackUnderflow
self.top -= 1
return self.data[self.top + 1]
def __str__(self):
return self.data[:self.top+1].__str__();
class StackUnderflow(Exception):
pass
if __name__ == '__main__':
stack = Stack()
try:
print(stack.pop())
except StackUnderflow:
print("Caught")
stack.push(3)
stack.push(True)
stack.push(8)
print(stack)
print(stack.pop())
print(stack)
print(stack.pop())
print(stack)
print(stack.pop())
print(stack)
try:
print(stack.pop())
except StackUnderflow:
print("Caught")