Skip to content
Python project #25Advanced

Huffman Compression

Build optimal prefix codes with a priority queue, encode and decode messages, and measure the space saved against UTF-8.

Estimated time
~4 hours to build
Files
4 files · 269 lines
Technologies
Python 3, heapq, collections.Counter, dataclasses

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

For each line of input, count character frequencies, build a Huffman tree with a priority queue (breaking ties deterministically), derive the codes, encode the message, decode it again to prove correctness, and report the number of distinct characters, the codes for the most frequent ones, the encoded size, bits per character, the saving compared with UTF-8 and the first bits of the encoding. Handle a message with only one distinct character and non-English text.

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

TextProject tree
huffman-compression/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

97 lines
Pythonmain.py
"""Huffman Compression: builds optimal prefix codes, encodes, decodes and measures savings.
Each non-empty input line is compressed as a separate message.
Ties between equal frequencies are broken deterministically, so the codes are repeatable.
"""
import heapq
import sys
from collections import Counter
from dataclasses import dataclass
@dataclass
class Node:
freq: int
symbol: str | None = None
left: "Node | None" = None
right: "Node | None" = None
def build_tree(text: str) -> Node:
counts = Counter(text)
heap = [(freq, i, Node(freq, sym)) for i, (sym, freq) in enumerate(sorted(counts.items()))]
heapq.heapify(heap)
order = len(heap)
if len(heap) == 1: # a single symbol still needs a 1-bit code
freq, _, leaf = heap[0]
return Node(freq, left=leaf)
while len(heap) > 1:
f1, _, a = heapq.heappop(heap)
f2, _, b = heapq.heappop(heap)
heapq.heappush(heap, (f1 + f2, order, Node(f1 + f2, left=a, right=b)))
order += 1
return heap[0][2]
def make_codes(node: Node, prefix: str = "", codes: dict[str, str] | None = None) -> dict[str, str]:
codes = {} if codes is None else codes
if node.symbol is not None:
codes[node.symbol] = prefix or "0"
else:
if node.left:
make_codes(node.left, prefix + "0", codes)
if node.right:
make_codes(node.right, prefix + "1", codes)
return codes
def encode(text: str, codes: dict[str, str]) -> str:
return "".join(codes[ch] for ch in text)
def decode(bits: str, root: Node) -> str:
out, node = [], root
for bit in bits:
node = node.left if bit == "0" else node.right
if node.symbol is not None:
out.append(node.symbol)
node = root
return "".join(out)
def label(symbol: str) -> str:
return {" ": "' '", "\t": "\\t"}.get(symbol, symbol)
def report(text: str, number: int) -> None:
root = build_tree(text)
codes = make_codes(root)
bits = encode(text, codes)
original_bits = len(text.encode("utf-8")) * 8
restored = decode(bits, root)
preview = text if len(text) <= 40 else text[:37] + "..."
print(f"== Message {number}: \"{preview}\" ==")
print(f" {len(text)} characters, {len(codes)} distinct, {original_bits} bits as UTF-8")
counts = Counter(text)
shown = sorted(codes.items(), key=lambda kv: (len(kv[1]), -counts[kv[0]], kv[0]))
for symbol, code in shown[:8]:
print(f" {label(symbol):<4}x{counts[symbol]:<3} {code}")
if len(shown) > 8:
print(f" ... {len(shown) - 8} more symbols")
average = len(bits) / len(text)
print(f" Encoded: {len(bits)} bits ({average:.2f} bits/char), saving {1 - len(bits) / original_bits:.1%}")
print(f" First bits: {bits[:48]}{'...' if len(bits) > 48 else ''}")
print(f" Decoded correctly: {'yes' if restored == text else 'NO'}\n")
def main() -> None:
messages = [line.rstrip("\n") for line in sys.stdin if line.strip()]
if not messages:
print("Nothing to compress.")
for number, text in enumerate(messages, 1):
report(text, number)
if __name__ == "__main__":
main()

What each file does

main.py
The Node class, tree building, code generation, encoding, decoding and the report.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
== Message 1: "abracadabra" ==
11 characters, 5 distinct, 88 bits as UTF-8
a x5 0
b x2 110
r x2 111
c x1 100
d x1 101
Encoded: 23 bits (2.09 bits/char), saving 73.9%
First bits: 01101110100010101101110
Decoded correctly: yes
== Message 2: "aaaaaaaaaa" ==
10 characters, 1 distinct, 80 bits as UTF-8
a x10 0
Encoded: 10 bits (1.00 bits/char), saving 87.5%
First bits: 0000000000
Decoded correctly: yes
== Message 3: "the quick brown fox jumps over the la..." ==
43 characters, 27 distinct, 344 bits as UTF-8
' ' x8 110
o x4 1011
e x3 1010
h x2 11100
r x2 11101
t x2 11110
u x2 11111
a x1 00000
... 19 more symbols
Encoded: 192 bits (4.47 bits/char), saving 44.2%
First bits: 111101110010101100110111111001100001001000110000...
Decoded correctly: yes
== Message 4: "mississippi river" ==
17 characters, 8 distinct, 136 bits as UTF-8
i x5 11
s x4 00
p x2 010
r x2 011
' ' x1 1000
e x1 1001
m x1 1010
v x1 1011
Encoded: 46 bits (2.71 bits/char), saving 66.2%
First bits: 1010110000110000110100101110000111110111001011
Decoded correctly: yes
== Message 5: "नमस्ते दुनिया" ==
13 characters, 12 distinct, 296 bits as UTF-8
न x2 011
ु x1 000
े x1 001
् x1 010
' ' x1 1000
त x1 1001
द x1 1010
म x1 1011
... 4 more symbols
Encoded: 47 bits (3.62 bits/char), saving 84.1%
First bits: 01110111101010100100110001010000011111111001110
Decoded correctly: yes
Input
abracadabra
aaaaaaaaaa
the quick brown fox jumps over the lazy dog
mississippi river
नमस्ते दुनिया

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/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

  1. 1Compute the entropy of each message and compare it with bits per character.
  2. 2Implement canonical Huffman codes.
  3. 3Build an adaptive (dynamic) Huffman coder.

Built and tested it yourself? Mark it to update your dashboard.