-
Notifications
You must be signed in to change notification settings - Fork 77
/
stack.py
96 lines (64 loc) · 1.52 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# Stack Big O complexity
# Push: O(1) - Constant Time
# Pop (remove): O(1) - Constant Time
# Top (top): O(1) - Constant Time
# Is Empty: O(1) - Constant Time
# Size: O(1) - Constant Time
class Emptiness(Exception):
pass
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if self.is_empty():
raise Emptiness('The Stack is empty')
return self.items.pop()
def is_empty(self):
return self.size() == 0
def top(self):
if self.is_empty():
raise Emptiness('The Stack is empty')
return self.items[-1]
def size(self):
return len(self.items)
stack = Stack()
print(stack.is_empty())
stack.push(1)
print(stack.items)
stack.push(2)
print(stack.items)
stack.push(3)
print(stack.items)
stack.push(4)
print(stack.items)
stack.push(5)
print(stack.items)
print(stack.is_empty())
print(stack.top())
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.is_empty())
print(stack.pop())
print(stack.is_empty())
# reversing a list
def reverse(bookshelf):
stack = Stack()
for book in bookshelf:
stack.push(book)
reversed_bookshelf = []
while not stack.is_empty():
reversed_bookshelf.append(stack.pop())
return reversed_bookshelf
bookshelf = [
'Harry Potter',
'Atomic Habits',
'Leonardo da Vinci',
'Sapiens',
'Peak'
]
reversed_bookshelf = reverse(bookshelf)
print(reversed_bookshelf)