-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstack.py
72 lines (54 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
61
62
63
64
65
66
67
68
69
70
71
72
class Stack:
def __init__(self):
self.items = []
def pop(self):
if self.isEmpty():
raise RuntimeError("Attempt to pop an empty stack")
topIdx = len(self.items)-1
item = self.items[topIdx]
del self.items[topIdx]
return item
def push(self,item):
self.items.append(item)
def top(self):
if self.isEmpty():
raise RuntimeError("Attempt to get top of empty stack")
topIdx = len(self.items)-1
return self.items[topIdx]
def isEmpty(self):
return len(self.items) == 0
def clear(self):
self.items = []
def main():
s = Stack()
items = list(range(10))
items2 = []
for k in items:
s.push(k)
if s.top() == 9:
print("Test 1 Passed")
else:
print("Test 1 Failed")
while not s.isEmpty():
items2.append(s.pop())
items2.reverse()
if items2 != items:
print("Test 2 Failed")
else:
print("Test 2 Passed")
try:
s.pop()
print("Test 3 Failed")
except RuntimeError:
print("Test 3 Passed")
except:
print("Test 3 Failed")
try:
s.top()
print("Test 4 Failed")
except RuntimeError:
print("Test 4 Passed")
except:
print("Test 4 Failed")
if __name__=="__main__":
main()