Warning
This implementation is inspired by a homework assignment from 15-213 at Carnegie Mellon University. It is intended for educational purposes only and is not suitable for production use.
A simple naive implementation of a stack in Python.
The purpose of this repo is to serve as an example of how to set up a GitHub Actions workflow.
A collection of items in which only the most recently added item may be removed. The latest added item is at the top. Basic operations are push and pop. Also known as "last-in, first-out" or LIFO.
— Paul E. Black, stack, Dictionary of Algorithms and Data Structures [online], NIST.
A stack is the right structure any time you need to reverse order or track state that must be unwound in reverse:
- Function call management — every programming language runtime uses a call stack to track active function calls and local variables.
- Undo/redo — text editors and drawing applications push actions onto a stack so they can be popped off in reverse order on undo.
- Expression parsing — compilers and calculators use stacks to evaluate arithmetic expressions and match parentheses.
- Depth-first search (DFS) — graph traversals use a stack (explicit or via recursion) to explore as deep as possible before backtracking.
- Browser history — the back button works by popping the most recently visited page off a stack.
- Python 3.6+
Clone the repository and install dependencies:
git clone https://github.com/icaoberg/python-stack.git
cd python-stack
pip install -r requirements.txtfrom Stack import Stack
s = Stack()
s.push(1)
s.push(2)
s.push(3)
print(s.size()) # 3
print(s.peek()) # 3
print(s.pop()) # 3
print(s.size()) # 2
print(s.is_empty()) # False
print(s.tolist()) # [1, 2]| Method | Description |
|---|---|
push(element) |
Add an element to the top of the stack |
pop() |
Remove and return the top element |
peek() |
Return the top element without removing it |
is_empty() |
Return True if the stack has no elements |
size() |
Return the number of elements in the stack |
tolist() |
Return a copy of the stack as a list |
pytest tests.pyIf you found this project helpful, consider buying me a coffee!
Copyright © icaoberg at Carnegie Mellon University. All rights reserved.
