Skip to content

Commit 8a8dca5

Browse files
* Added type hints
* Added test * Formated code
1 parent 696cd47 commit 8a8dca5

File tree

1 file changed

+27
-24
lines changed

1 file changed

+27
-24
lines changed

data_structures/stacks/stack.py

Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
__author__ = "Omkar Pathak"
2-
3-
41
class Stack:
52
"""A stack is an abstract data type that serves as a collection of
63
elements with two principal operations: push() and pop(). push() adds an
@@ -11,14 +8,14 @@ class Stack:
118
https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
129
"""
1310

14-
def __init__(self, limit=10):
11+
def __init__(self, limit: int = 10):
1512
self.stack = []
1613
self.limit = limit
1714

18-
def __bool__(self):
15+
def __bool__(self) -> bool:
1916
return bool(self.stack)
2017

21-
def __str__(self):
18+
def __str__(self) -> str:
2219
return str(self.stack)
2320

2421
def push(self, data):
@@ -29,21 +26,24 @@ def push(self, data):
2926

3027
def pop(self):
3128
""" Pop an element off of the top of the stack."""
32-
if self.stack:
33-
return self.stack.pop()
34-
else:
29+
if self.is_empty():
3530
raise IndexError("pop from an empty stack")
31+
return self.stack.pop()
3632

3733
def peek(self):
3834
""" Peek at the top-most element of the stack."""
39-
if self.stack:
40-
return self.stack[-1]
35+
if self.is_empty():
36+
raise IndexError("peek from an empty stack")
37+
return self.stack[-1]
4138

42-
def is_empty(self):
39+
def is_empty(self) -> bool:
4340
""" Check if a stack is empty."""
4441
return not bool(self.stack)
4542

46-
def size(self):
43+
def is_full(self) -> bool:
44+
return self.size() == self.limit
45+
46+
def size(self) -> int:
4747
""" Return the size of the stack."""
4848
return len(self.stack)
4949

@@ -57,19 +57,22 @@ class StackOverflowError(BaseException):
5757

5858

5959
if __name__ == "__main__":
60-
stack = Stack()
60+
stack = Stack(10)
6161
for i in range(10):
6262
stack.push(i)
6363

64-
print("Stack demonstration:\n")
65-
print("Initial stack: " + str(stack))
66-
print("pop(): " + str(stack.pop()))
67-
print("After pop(), the stack is now: " + str(stack))
68-
print("peek(): " + str(stack.peek()))
64+
assert stack.is_full()
65+
assert str(stack) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
66+
assert stack.pop() == 9
67+
assert stack.peek() == 8
68+
6969
stack.push(100)
70-
print("After push(100), the stack is now: " + str(stack))
71-
print("is_empty(): " + str(stack.is_empty()))
72-
print("size(): " + str(stack.size()))
70+
assert str(stack) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 100])
71+
72+
assert not stack.is_empty()
73+
assert stack.size() == 10
74+
7375
num = 5
74-
if num in stack:
75-
print(f"{num} is in stack")
76+
assert num in stack
77+
num = 55
78+
assert num not in stack

0 commit comments

Comments
 (0)