SimpleDSA
A simple and intuitive implementation of data structures and algorithms in Python.
Installation
pip install simpledsa
Usage
Priority Queue
from simpledsa import PriorityQueue
pq = PriorityQueue()
max_pq = PriorityQueue(lambda x: -x)
pq.push(3)
pq.push(1)
pq.push(4)
print(pq.pop())
print(pq.pop())
print(pq.pop())
task_queue = PriorityQueue()
task_queue.push("Write docs", priority=2)
task_queue.push("Fix bug", priority=1)
task_queue.push("Add feature", priority=3)
print(task_queue.pop())
print(task_queue.pop())
print(task_queue.pop())
if not pq:
print("Queue is empty")
print(len(pq))
task_queue.push("Important task", priority=1)
print(task_queue.peek())
Advanced Usage Examples
Context Manager (with statement)
from simpledsa import PriorityQueue
with PriorityQueue() as pq:
pq.push("task1", 1)
pq.push("task2", 2)
process_tasks(pq)
with PriorityQueue() as pq:
pq.extend(tasks)
while pq:
process(pq.pop())
Batch Operations
pq = PriorityQueue()
pq.extend([1, 2, 3])
pq.extend([("task1", 1), ("task2", 2)])
pq = PriorityQueue.from_items([1, 2, 3])
pq = PriorityQueue.from_items_with_priority([("task1", 1), ("task2", 2)])
Iteration
pq = PriorityQueue.from_items([3, 1, 4, 1, 5])
for item in pq:
print(item)
for item in pq.pop_all():
process(item)
Queue Merging
pq1 = PriorityQueue.from_items([1, 3, 5])
pq2 = PriorityQueue.from_items([2, 4, 6])
merged = PriorityQueue.merge([pq1, pq2])
Priority Functions
from simpledsa import PriorityQueue, priority_functions
max_pq = PriorityQueue(priority_functions.reverse)
max_pq.extend([1, 2, 3])
print(max_pq.pop())
length_pq = PriorityQueue(priority_functions.by_length)
length_pq.extend(["a", "ccc", "bb"])
print(length_pq.pop())
class Task:
def __init__(self, name, priority):
self.name = name
self.priority = priority
task_pq = PriorityQueue(priority_functions.by_attr('priority'))
tasks = [Task("A", 2), Task("B", 1), Task("C", 3)]
task_pq.extend(tasks)
Features
- Supports both min-heap (default) and max-heap behavior
- Items can serve as their own priority or have explicit priorities
- Stable sorting: items with equal priorities maintain their insertion order
- Standard Python container operations:
len()
, boolean evaluation - O(log n) push and pop operations
- O(1) peek and is_empty operations
License
This project is licensed under the MIT License - see the LICENSE file for details.
Development
Setting up development environment
git clone https://github.com/dsalathe/simpledsa.git
cd simpledsa
curl -sSL https://install.python-poetry.org | python3 -
poetry install
poetry run pytest
poetry run black .
poetry run isort .
poetry run mypy simpledsa
Building documentation
cd docs
poetry run make html
The documentation will be available in docs/_build/html
.
Publishing a new version
- Update version in pyproject.toml
- Create and push a new tag:
git tag v0.1.1
git push origin v0.1.1
The GitHub Action will automatically build and publish to PyPI.