Skip to content

Commit c929114

Browse files
Michael CCMichae1CC
Michael CC
authored andcommitted
Added a stack and queue implementation for python3
1 parent f6ce7e4 commit c929114

File tree

3 files changed

+153
-3
lines changed

3 files changed

+153
-3
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#!/usr/bin/env python3
2+
3+
__author__ = "Michael Ciccotosto-Camp"
4+
5+
import abc
6+
7+
from collections.abc import Sized
8+
from typing import TypeVar, Generic
9+
10+
11+
T = TypeVar("T")
12+
13+
14+
class IStack(Generic[T], Sized, abc.ABC):
15+
@abc.abstractmethod
16+
def pop(self) -> T:
17+
"""
18+
Removes the last element from the stack and returns it.
19+
"""
20+
...
21+
22+
@abc.abstractmethod
23+
def push(self, element: T) -> int:
24+
"""
25+
Adds an element to the end of the stack and returns the
26+
new length of the stack.
27+
"""
28+
...
29+
30+
@abc.abstractmethod
31+
def top(self) -> T:
32+
"""
33+
Returns the first element of the stack.
34+
"""
35+
...
36+
37+
38+
class Stack(IStack[T]):
39+
def __init__(self) -> None:
40+
self.__list: list[T] = []
41+
42+
def pop(self) -> T:
43+
return self.__list.pop()
44+
45+
def push(self, element: T) -> int:
46+
self.__list.append(element)
47+
return len(self)
48+
49+
def top(self) -> T:
50+
return self.__list[-1]
51+
52+
def __len__(self) -> int:
53+
return len(self.__list)
54+
55+
def __str__(self) -> str:
56+
return str(self.__list)
57+
58+
59+
def main() -> None:
60+
int_stack: Stack[int] = Stack()
61+
62+
int_stack.push(4)
63+
int_stack.push(5)
64+
int_stack.push(9)
65+
66+
print(int_stack.pop())
67+
print(len(int_stack))
68+
print(int_stack.top())
69+
70+
71+
if __name__ == "__main__":
72+
main()
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#!/usr/bin/env python3
2+
3+
__author__ = "Michael Ciccotosto-Camp"
4+
5+
import abc
6+
7+
from collections.abc import Sized
8+
from typing import TypeVar, Generic
9+
10+
11+
T = TypeVar("T")
12+
13+
14+
class IQueue(Generic[T], Sized, abc.ABC):
15+
@abc.abstractmethod
16+
def dequeue(self) -> T:
17+
"""
18+
Removes the first element from the queue and returns it.
19+
"""
20+
...
21+
22+
@abc.abstractmethod
23+
def enqueue(self, element: T) -> int:
24+
"""
25+
Add an element at the end of the queue and returns the
26+
new size of the queue.
27+
"""
28+
...
29+
30+
@abc.abstractmethod
31+
def front(self) -> T:
32+
"""
33+
Returns the first element in the queue without removing it.
34+
"""
35+
...
36+
37+
38+
class Queue(IQueue[T]):
39+
def __init__(self) -> None:
40+
self.__list: list[T] = list()
41+
42+
def dequeue(self) -> T:
43+
return self.__list.pop(0)
44+
45+
def enqueue(self, element: T) -> int:
46+
self.__list.append(element)
47+
return len(self)
48+
49+
def front(self) -> T:
50+
return self.__list[0]
51+
52+
def __len__(self) -> int:
53+
return len(self.__list)
54+
55+
def __str__(self) -> str:
56+
return str(self.__list)
57+
58+
59+
def main() -> None:
60+
int_queue: Queue[int] = Queue()
61+
62+
int_queue.enqueue(4)
63+
int_queue.enqueue(5)
64+
int_queue.enqueue(9)
65+
66+
print(int_queue.dequeue())
67+
print(len(int_queue))
68+
print(int_queue.front())
69+
70+
71+
if __name__ == "__main__":
72+
main()

contents/stacks_and_queues/stacks_and_queues.md

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,20 @@
22

33
Stacks and Queues are two sides of the same coin in computer science. They are both simple data structures that hold multiple elements, but allow you to use a single element at a time. The biggest difference between the two structures is the order in which you can access the elements in the data structure.
44

5-
In *stacks*, data follows *Last In, First Out* (LIFO), which basically means that whichever element you put in last will be the first element you take out. It acts exactly like a stack in real life. If you put a book on a stack of other books, the first book you will look at when sifting through the stack will be the book you just put on the stack.
5+
In _stacks_, data follows _Last In, First Out_ (LIFO), which basically means that whichever element you put in last will be the first element you take out. It acts exactly like a stack in real life. If you put a book on a stack of other books, the first book you will look at when sifting through the stack will be the book you just put on the stack.
66

7-
In *Queues*, data follows *First In, First Out* (FIFO), which means that whichever element you put in first will be the first element you take out. Imagine a queue of people. It would be unfair if the first person in line for groceries were not the first person to receive attention once the attendant finally shows up.
7+
In _Queues_, data follows _First In, First Out_ (FIFO), which means that whichever element you put in first will be the first element you take out. Imagine a queue of people. It would be unfair if the first person in line for groceries were not the first person to receive attention once the attendant finally shows up.
88

99
For the most part, though, queues and stacks are treated the same way. There must be a way to:
10+
1011
1. look at the first element (`top()`)
1112
2. to remove the first element (`pop()`)
1213
3. to push elements onto the data structure (`push()`)
1314

1415
The notation for this depends on the language you are using. Queues, for example, will often use `dequeue()` instead of `pop()` and `front()` instead of `top()`. You will see the language-specific details in the source code under the algorithms in this book, so for now it's simply important to know what stacks and queues are and how to access elements held within them.
1516

1617
## Example Code
18+
1719
Here is a simple implementation of a stack:
1820
{% method %}
1921
{% sample lang="ts" %}
@@ -24,6 +26,8 @@ Here is a simple implementation of a stack:
2426
[import, lang:"cpp"](code/cpp/stack.cpp)
2527
{% sample lang="rust" %}
2628
[import, lang:"rust"](code/rust/Stack.rs)
29+
{% sample lang="python" %}
30+
[import, lang:"python"](code/python/stack.py)
2731
{% endmethod %}
2832

2933
Here is a simple implementation of a queue:
@@ -36,9 +40,10 @@ Here is a simple implementation of a queue:
3640
[import, lang:"cpp"](code/cpp/queue.cpp)
3741
{% sample lang="rust" %}
3842
[import, lang:"rust" ](code/rust/Queue.rs)
43+
{% sample lang="python" %}
44+
[import, lang:"python"](code/python/queue.py)
3945
{% endmethod %}
4046

41-
4247
## License
4348

4449
##### Code Examples
@@ -54,4 +59,5 @@ The text of this chapter was written by [James Schloss](https://github.com/leios
5459
##### Pull Requests
5560

5661
After initial licensing ([#560](https://github.com/algorithm-archivists/algorithm-archive/pull/560)), the following pull requests have modified the text or graphics of this chapter:
62+
5763
- none

0 commit comments

Comments
 (0)