Skip to content

Commit 818c322

Browse files
committed
Added stack.py
1 parent a3f1bd0 commit 818c322

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

stack.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class Stack:
2+
class EmptyStackError(Exception):
3+
def __str__(self) -> str:
4+
return "Stack is empty."
5+
6+
def __init__(self) -> None:
7+
self._data: list[object] = []
8+
self._size: int = 0
9+
10+
def __len__(self) -> int:
11+
return self._size
12+
13+
def length(self) -> int:
14+
return self.__len__()
15+
16+
def __str__(self) -> str:
17+
return str(self._data)
18+
19+
def is_empty(self) -> bool:
20+
return self._size == 0
21+
22+
def top(self) -> object:
23+
if self.is_empty():
24+
raise Stack.EmptyStackError
25+
return self._data[-1]
26+
27+
def push(self, element: object) -> None:
28+
self._data.append(element)
29+
self._size += 1
30+
31+
def pop(self) -> object:
32+
if self.is_empty():
33+
raise Stack.EmptyStackError
34+
self._size -= 1
35+
return self._data.pop()
36+
37+
38+
if __name__ == '__main__':
39+
stack = Stack()
40+
print(stack.is_empty())
41+
for i in range(10):
42+
stack.push(i)
43+
print(stack.top())
44+
print(stack)
45+
print(len(stack))
46+
print(stack.length())
47+
print(stack.is_empty())
48+
for i in range(10):
49+
print(stack.pop())
50+
print(stack.is_empty())

0 commit comments

Comments
 (0)