Skip to content

Commit 187ccb8

Browse files
committed
add stack minimal implementation with tests
1 parent 5ef1be0 commit 187ccb8

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

data_structures/stack/stack.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Stack:
2+
"""
3+
Simple stack implementation using a list
4+
"""
5+
6+
def __init__(self) -> None:
7+
self.items = []
8+
9+
def is_empty(self) -> bool:
10+
"""check if the stack is empty"""
11+
return self.items == []
12+
13+
def push(self, item: any) -> None:
14+
"""push an item to the top of the stack"""
15+
self.items.append(item)
16+
17+
def pop(self) -> any:
18+
"""pop the top item of the stack"""
19+
return self.items.pop()
20+
21+
def peek(self) -> any:
22+
"""peek at the top item of the stack"""
23+
return self.items[len(self.items)-1]
24+
25+
def size(self) -> int:
26+
"""return the size of the stack"""
27+
return len(self.items)
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import unittest
2+
from stack import Stack
3+
4+
5+
class Test_Stack(unittest.TestCase):
6+
7+
def test_is_empty(self: any) -> None:
8+
stack = Stack()
9+
self.assertTrue(stack.is_empty())
10+
stack.push(1)
11+
self.assertFalse(stack.is_empty())
12+
13+
def test_push(self):
14+
stack = Stack()
15+
stack.push(1)
16+
self.assertEqual(stack.peek(), 1)
17+
stack.push(2)
18+
self.assertEqual(stack.peek(), 2)
19+
20+
def test_pop(self):
21+
stack = Stack()
22+
stack.push(1)
23+
stack.push(2)
24+
self.assertEqual(stack.pop(), 2)
25+
self.assertEqual(stack.pop(), 1)
26+
27+
def test_peek(self):
28+
stack = Stack()
29+
stack.push(1)
30+
stack.push(2)
31+
self.assertEqual(stack.peek(), 2)
32+
self.assertEqual(stack.peek(), 2)
33+
34+
def test_size(self):
35+
stack = Stack()
36+
self.assertEqual(stack.size(), 0)
37+
stack.push(1)
38+
self.assertEqual(stack.size(), 1)
39+
stack.push(2)
40+
self.assertEqual(stack.size(), 2)
41+
42+
43+
if __name__ == '__main__':
44+
unittest.main()

0 commit comments

Comments
 (0)