Build a tested algorithms library
Publish a Python package of your own data structures and algorithms with tests and benchmarks.
By Invicly Tech, , in Data Structures & Algorithms. About 12 minutes to read.
In short
Building your own algorithms library turns scattered exercises into a single tested codebase you understand completely. Each structure gets an implementation, tests that cover edge cases, a documented complexity and a benchmark against Python's built-ins. It becomes both a portfolio piece and a personal reference.
Explained simply
By now you have written many small solutions: a heap here, a binary search there, a graph search in some notebook. They are scattered, half-tested and hard to find again. Building a library means gathering them into one Python package that you can install, import and trust.
Trust comes from tests. A test is a small piece of code that runs your function and checks the answer. If you change something later and break it, the test fails at once and tells you where. Good tests try the boring cases (an empty list, one item, all items equal), because that is where bugs hide.
You will also measure speed. A benchmark runs your code many times on the same input and records how long it takes. Comparing your merge sort with Python's sorted shows how much a fast built-in written in C really helps, and doubling the input size shows the growth rate you predicted.
Finally you write down the cost of every function, its time and space complexity, and publish the project with a clear README. The result is a portfolio piece you can show an employer and a reference you understand line by line.
Press Play on a diagram to walk through it one step at a time.
- 1README and docs
Usage plus a complexity table.
- 2Benchmarks
timeit comparisons with built-ins.
- 3Tests
pytest cases: empty, single, duplicates, large.
- 4Algorithms
Sorting, graphs, DP helpers.
- 5Data structures
Dynamic array, linked list, heap, trie, DSU, Fenwick.
- 1Write tests first
Edge cases and a property test.
- 2Implement
Until every test passes.
- 3Document
Docstring with time and space.
- 4Benchmark
Against the built-in, at n, 2n, 4n.
- 5Commit
CI runs everything again.
- Back to step 1
In depth
A clean project layout
Use the src layout: your package lives in src/mylib/ and tests live in tests/, outside the package. A small pyproject.toml describes the project. With a recent setuptools, a [build-system] table (requires = ["setuptools>=61"], build-backend = "setuptools.build_meta") and a [project] table with name, version and requires-python are enough; setuptools finds packages under src/ automatically.
Install it in editable mode with pip install -e . inside a virtual environment. Now import mylib works from anywhere, and code changes are picked up without reinstalling. The src layout has one real benefit: tests import the installed package, not the folder they happen to sit next to, so a file you forgot to include shows up as a test failure on your machine instead of on someone else's.
Group modules by topic: structures (heap, trie, union-find, Fenwick), sorting, searching, graphs and dp.
- pyproject.toml
- Name, version, requires-python
- pytest settings
- src/mylib/
- structures/ (heap, trie, dsu)
- sorting.py, searching.py
- graphs.py, dp.py
- tests/
- test_heap.py
- test_sorting.py
- test_graphs.py
- bench/
- bench_sorting.py
- README.md and LICENSE
Tests that actually catch bugs
Start with pytest: any function named test_something in a file named test_*.py is collected and run by pytest. Use plain assert statements; pytest shows the values when one fails.
@pytest.mark.parametrize runs one test body over a list of inputs, which is perfect for edge cases: empty input, one element, two elements, all duplicates, already sorted, reverse sorted, negative numbers and the target missing. Add a regression test every time you find a bug, so it can never return.
Property-based testing goes further. The Hypothesis library generates hundreds of random inputs from a description such as st.lists(st.integers()) and checks a property, for example "my sort equals sorted()". When it finds a failure it shrinks the input to the smallest example that still fails, which makes debugging much easier. For data structures, compare a random sequence of operations against a trusted model like heapq or a plain dict.
- pytest -q runs everything quietly
- pytest -k heap runs only tests matching heap
- pytest --cov=mylib needs the pytest-cov plugin
- Every bug you fix gets a regression test
Benchmarking without fooling yourself
Use timeit, not a single time.time() call. timeit.repeat(stmt, number=5, repeat=5) runs the code 5 times per round for 5 rounds and returns each round's total. Take the minimum: background noise can only make code slower, so the fastest round is the best estimate of the real cost. From a shell, python -m timeit -s "setup" "statement" does the same and picks the loop count for you.
Always copy mutable inputs inside the timed code (sorting an already sorted list is a different benchmark), and use the same random seed so runs are comparable.
The most useful test is doubling. Time the function at n, 2n and 4n. If time roughly doubles, it is O(n); a bit more than double suggests O(n log n); four times means O(n^2). Expect Python's built-ins such as sorted and heapq to beat your pure Python versions by a large factor, because they run in C.
- O(n)
- Linear scan, prefix sums
- Sliding window
- O(n log n)
- Merge sort, heap sort
- Sorting plus a scan
- O(n^2)
- Insertion sort
- Nested loops over pairs
Documenting complexity and the API
Every public function gets a docstring with what it takes, what it returns, what it raises, and its cost. Write Time: O(log n) and Space: O(1), and say when a bound is amortized (averaged over many calls), as with a dynamic array's append, or expected rather than worst case, as with randomized quicksort or hash lookups.
Add type hints such as def binary_search(xs: list[int], target: int) -> int. They document the contract and let tools like mypy check callers.
Keep the API small and consistent. If one structure uses push and pop, the others should too. Decide once what "not found" means (return -1, return None, or raise) and use it everywhere. Put a single table in the README listing every function with its time and space, and make sure it matches the docstrings.
- State worst, amortized or expected explicitly
- One convention for not found across the library
- Type hints double as documentation
Publishing: README, CI and versioning
A good README answers four questions in order: what is this, how do I install it, how do I use it (a five-line example), and what is inside (the complexity table). Add a LICENSE file, such as MIT, so others may legally reuse the code.
Set up continuous integration (CI): a GitHub Actions workflow that installs the package and runs pytest on every push and pull request, ideally on two or three Python versions. A green badge in the README shows the tests pass.
You can go further and build a distribution with python -m build, which writes a wheel and a source archive into dist/, and upload it to PyPI with twine. For a learning project, a tidy GitHub repository with tags such as v0.1.0 is often enough.
- 1Checkout
Get the commit.
- 2Set up Python
One job per version.
- 3Install
pip install -e . plus test tools.
- 4Run pytest
Fail the build on any failure.
- 5Report
Green or red check on the commit.
Learn it in 5 short steps
About 1h 35m each. Track them with a timer in your plan.
- 1Implement core structures in one package~1h 35m
- 2Write pytest tests including edge cases~1h 35m
- 3Benchmark against built-ins with timeit~1h 35m
- 4Document complexity for every function~1h 35m
- 5Publish the repo with a README~1h 35m
Key points
- Write tests first for the edge cases that broke your solutions before.
- Document time and space complexity in every docstring.
- Benchmarks show when constants matter, such as your heap versus heapq.
- Keep the public API small and consistent across structures.
Key terms
Tap a card to flip it. 0/3 known
Examples
import random
from mylib.sorting import merge_sort, quicksort
def test_sorts_match_builtin():
for _ in range(200):
xs = [random.randint(-50, 50) for _ in range(random.randint(0, 40))]
assert merge_sort(xs[:]) == sorted(xs)
assert quicksort(xs[:]) == sorted(xs)
def test_empty_and_single():
assert merge_sort([]) == [] and merge_sort([1]) == [1]Run with: pytest -q
Testing a MinHeap with edge cases and Hypothesis
Step 1: list edge cases: empty, one item, duplicates, negatives. Step 2: write one parametrized test that pushes everything and checks that popping returns sorted order. Step 3: add a Hypothesis test with the same check on random lists, so cases you never thought of are tried too. Step 4: run pytest -q. If Hypothesis finds a bug, it prints the smallest failing list, for example [0, -1], which points straight at a sift-down mistake.
import pytest
from hypothesis import given, strategies as st
from mylib.structures.heap import MinHeap
def drain(xs):
h = MinHeap()
for x in xs: h.push(x)
return [h.pop() for _ in xs]
@pytest.mark.parametrize("xs", [[], [1], [2, 2, 2], [5, -1, 3, 0]])
def test_edge_cases(xs):
assert drain(xs) == sorted(xs)
@given(st.lists(st.integers()))
def test_matches_sorted(xs):
assert drain(xs) == sorted(xs)Benchmarking merge sort against sorted with doubling
Step 1: fix a seed and create random lists of size 10,000, 20,000 and 40,000. Step 2: time each sort with timeit.repeat and keep the minimum. Step 3: copy the list inside the timed lambda so every run sorts unsorted data. Step 4: read the output. Your merge sort should grow a little faster than 2x per doubling (O(n log n)), and sorted() should be much faster at every size, because Timsort runs in C.
import random, timeit
from mylib.sorting import merge_sort
random.seed(42)
for n in (10_000, 20_000, 40_000):
xs = [random.random() for _ in range(n)]
mine = min(timeit.repeat(lambda: merge_sort(xs[:]), number=5, repeat=5))
ref = min(timeit.repeat(lambda: sorted(xs), number=5, repeat=5))
print(f"n={n:>6} merge_sort {mine:.3f}s sorted {ref:.3f}s")Quick reference
- pip install -e . installs your package in editable mode inside a virtual environment
- pytest finds test_*.py files and test_* functions; run pytest -q for short output
- @pytest.mark.parametrize runs one test over many inputs: ideal for edge cases
- Hypothesis: @given(st.lists(st.integers())) generates inputs and shrinks failures
- timeit.repeat(...) then min(...): the fastest run is the best estimate
- Doubling test: x2 time is O(n), a bit over x2 is O(n log n), x4 is O(n^2)
- Docstrings say Time and Space, and whether a bound is amortized or expected
- python -m build writes a wheel and an sdist into dist/
Common mistakes
- Testing only the happy path with small sorted inputs.
- Copying implementations without being able to rewrite them from memory.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a parametrized pytest test for binary_search(xs, target), which returns an index or -1. Cover empty input, one element (found and not found), first, last and missing targets.
- Exercise 2medium
Write growth(fn) that times fn on random lists of size 1,000, 2,000 and 4,000 and prints how many times slower each size is than the previous one. Run it on insertion sort and on merge sort.
- Exercise 3hard
Write a Hypothesis test that runs a random sequence of push and pop operations on your MinHeap and on heapq side by side, and checks they always agree. Assume MinHeap supports len().
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Why write my own heap or sort when Python already has heapq and sorted?
- To learn and to prove you understand them. In real projects you should use the built-ins, which are faster and well tested; your library's benchmarks will show that clearly.
- Do I need 100% test coverage?
- No. Coverage tells you which lines ran, not whether the answers were checked. Aim for every public function tested on its edge cases plus a property test against a reference.
- Should I publish my library on PyPI?
- It is optional. A clean GitHub repository with a README, tests and passing CI is what most reviewers look at. If you publish, choose a unique name and try TestPyPI first.