Skip to content

Commit b82d43a

Browse files
Added stack (#15)
* update project structure * add stack
1 parent 0f5c050 commit b82d43a

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed

data_structures/stack/stack.py

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
from typing import Any
2+
3+
4+
class Stack:
5+
def __init__(self, capacity: int = 10) -> None:
6+
self.stack = []
7+
self.capacity = capacity
8+
9+
def __len__(self):
10+
"""
11+
>>> stack = Stack()
12+
>>> for i in range(0, 10):
13+
... stack.push(i)
14+
>>> len(stack)
15+
10
16+
"""
17+
return len(self.stack)
18+
19+
def size(self) -> int:
20+
"""
21+
>>> stack = Stack()
22+
>>> for i in range(0, 10):
23+
... assert len(stack) == i
24+
... stack.push(i)
25+
>>> stack.size()
26+
10
27+
"""
28+
return len(self)
29+
30+
def is_full(self) -> bool:
31+
"""
32+
>>> stack = Stack()
33+
>>> for i in range(0, 10):
34+
... stack.push(i)
35+
>>> stack.is_full()
36+
True
37+
"""
38+
return len(self) == self.capacity
39+
40+
def is_empty(self) -> bool:
41+
"""
42+
>>> stack = Stack()
43+
>>> stack.is_empty()
44+
True
45+
>>> stack.push(666)
46+
>>> stack.push(999)
47+
>>> stack.is_empty()
48+
False
49+
"""
50+
return len(self) == 0
51+
52+
def push(self, item: Any) -> None:
53+
"""
54+
>>> stack = Stack()
55+
>>> for i in range(0, 10):
56+
... stack.push(i)
57+
>>> stack.push(666)
58+
Traceback (most recent call last):
59+
...
60+
ValueError: stack is full
61+
"""
62+
if self.is_full():
63+
raise ValueError("stack is full")
64+
self.stack.append(item)
65+
66+
def pop(self) -> Any:
67+
"""
68+
>>> stack = Stack()
69+
>>> stack.pop()
70+
Traceback (most recent call last):
71+
...
72+
ValueError: stack is empty
73+
>>> for i in range(0, 10):
74+
... stack.push(i)
75+
>>> for i in range(9, -1, -1):
76+
... assert stack.pop() == i
77+
"""
78+
if self.is_empty():
79+
raise ValueError("stack is empty")
80+
return self.stack.pop()
81+
82+
def peek(self) -> Any:
83+
"""
84+
>>> stack = Stack()
85+
>>> stack.peek()
86+
Traceback (most recent call last):
87+
...
88+
ValueError: stack is empty
89+
>>> stack.push('a')
90+
>>> stack.push('b')
91+
>>> stack.push('c')
92+
>>> stack.peek()
93+
'c'
94+
"""
95+
if self.is_empty():
96+
raise ValueError("stack is empty")
97+
return self.stack[-1]
98+
99+
100+
if __name__ == "__main__":
101+
from doctest import testmod
102+
103+
testmod()

0 commit comments

Comments
 (0)