Introduction
Huffman coding, invented in 1952, is still part of ZIP, PNG and JPEG. Frequent characters get short codes and rare ones long codes, and no code is a prefix of another, so the bit stream can be decoded unambiguously.
Problem statement
Objectives
- Use heapq as a priority queue
- Build and traverse binary trees recursively
- Encode and decode with prefix codes
- Reason about compression ratios
Features
- Deterministic Huffman trees
- Code table for the most frequent symbols
- Encoding, decoding and verification
- Savings versus UTF-8
- Single-symbol and Unicode messages
Concepts demonstrated
- Greedy algorithms
- Binary trees
- Prefix codes
- Information theory basics
System architecture
build_tree puts (frequency, order, node) tuples on a heap; the order number breaks ties so results are repeatable. It repeatedly merges the two least frequent nodes. A single-symbol message gets a root with one child so the code is '0'. make_codes walks the tree adding 0 for left and 1 for right. decode follows bits from the root until it reaches a leaf. report prints the statistics and verifies the round trip.
Folder structure
Complete source code
main.py
What each file does
- main.py
- The Node class, tree building, code generation, encoding, decoding and the report.
How to run it
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
abracadabra aaaaaaaaaa the quick brown fox jumps over the lazy dog mississippi river नमस्ते दुनिया
Testing
- Run
python main.py < tests/sample-input.txtand compare withtests/expected-output.txt. - 'abracadabra' compresses from 88 bits to 23, with 'a' getting the one-bit code 0.
- 'aaaaaaaaaa' (one distinct symbol) still encodes to 10 bits and decodes correctly.
- The Hindi message saves 84.1% because each Devanagari character takes 3 bytes in UTF-8.
Common errors
TypeError: '<' not supported between Node instances
Put a unique order number before the node in each heap tuple so nodes are never compared.
A one-character message has an empty code
Give single-symbol trees a root with one child, so the code is '0'.
Possible improvements
- Write the encoded bits to a binary file with the tree header
- Compress whole files instead of lines
- Compare with zlib from the standard library
Additional challenges
- 1Compute the entropy of each message and compare it with bits per character.
- 2Implement canonical Huffman codes.
- 3Build an adaptive (dynamic) Huffman coder.
Built and tested it yourself? Mark it to update your dashboard.