DEV Community

GTU Hero
GTU Hero

Posted on

Huffman Coding in Under 40 Lines of Python: Build the Tree, Get the Codes, Prove the Compression (GTU Data Compression)

If you study Data Compression, Huffman coding is the first algorithm you are expected to do in your sleep: given symbol frequencies, build the tree, assign codes, compute the average code length, and compare it with fixed length coding. It is also a lovely little greedy algorithm to implement. Let us do both: write it with Python's heapq, then do the same example by hand the way you would draw it in an exam.

Disclosure: GTU Hero is my project (link at the end). The code and numbers here are my own practice example, run before posting.

The idea

Huffman coding gives short codes to frequent symbols and long codes to rare ones, and guarantees that no code is a prefix of another (a prefix code), so the bit stream can be decoded without separators. The greedy rule is simple:

  1. Put every symbol in a min priority queue keyed by frequency.
  2. Remove the two smallest, join them under a new node whose frequency is their sum, put that node back.
  3. Repeat until one node is left. That node is the root.
  4. Walk the tree: left edge = 0, right edge = 1. The path to each leaf is its code.

The example

Six symbols in a 100 character file:

Symbol a b c d e f
Frequency 5 9 12 13 16 45

With fixed length coding we need 3 bits per symbol (2^3 = 8 is the smallest power of two that is at least 6), so 100 x 3 = 300 bits.

The code

import heapq
from itertools import count

def huffman(freq):
    tie = count()
    heap = [(f, next(tie), sym) for sym, f in freq.items()]
    heapq.heapify(heap)
    while len(heap) > 1:
        f1, _, left = heapq.heappop(heap)
        f2, _, right = heapq.heappop(heap)
        print(f"merge {f1:>3} + {f2:>3} = {f1 + f2:>3}")
        heapq.heappush(heap, (f1 + f2, next(tie), (left, right)))
    codes = {}
    def walk(node, prefix):
        if isinstance(node, str):
            codes[node] = prefix or "0"
            return
        walk(node[0], prefix + "0")
        walk(node[1], prefix + "1")
    walk(heap[0][2], "")
    return codes

freq = {"a": 5, "b": 9, "c": 12, "d": 13, "e": 16, "f": 45}
codes = huffman(freq)
total = sum(freq.values())
bits = sum(freq[s] * len(codes[s]) for s in freq)
for s in sorted(codes):
    print(s, freq[s], codes[s])
print("total bits:", bits, "fixed 3-bit:", 3 * total)
print("average length:", bits / total)
Enter fullscreen mode Exit fullscreen mode

Two small details:

  • The tie counter is there because Python compares tuples element by element. If two nodes have the same frequency, it would try to compare a string with a tuple and crash. The counter breaks ties first.
  • Internal nodes are just (left, right) tuples and leaves are strings, so isinstance(node, str) is the leaf test.

The output

merge   5 +   9 =  14
merge  12 +  13 =  25
merge  14 +  16 =  30
merge  25 +  30 =  55
merge  45 +  55 = 100
a 5 1100
b 9 1101
c 12 100
d 13 101
e 16 111
f 45 0
total bits: 224 fixed 3-bit: 300
average length: 2.24
Enter fullscreen mode Exit fullscreen mode

The same thing by hand

Write the sorted list and merge the two smallest each round. Re-sort after every merge, this is where most people slip.

Round 1: a5  b9  c12 d13 e16 f45   -> merge a5 + b9  = 14
Round 2: c12 d13 (14) e16 f45      -> merge c12 + d13 = 25
Round 3: (14) e16 (25) f45         -> merge 14 + e16 = 30
Round 4: (25) (30) f45             -> merge 25 + 30 = 55
Round 5: f45 (55)                  -> merge 45 + 55 = 100 (root)
Enter fullscreen mode Exit fullscreen mode

Tree, with 0 on the left and 1 on the right:

            (100)
           0/   \1
          f45   (55)
               0/   \1
             (25)   (30)
            0/ \1   0/  \1
           c12 d13 (14)  e16
                   0/ \1
                   a5  b9
Enter fullscreen mode Exit fullscreen mode

Reading paths: f = 0, c = 100, d = 101, e = 111, a = 1100, b = 1101.

Proving the compression

Average code length:

L = (45 x 1 + 12 x 3 + 13 x 3 + 16 x 3 + 5 x 4 + 9 x 4) / 100
  = (45 + 36 + 39 + 48 + 20 + 36) / 100
  = 224 / 100 = 2.24 bits per symbol
Enter fullscreen mode Exit fullscreen mode

Compared with 3 bits fixed, that is 224 bits instead of 300, a saving of 76 bits, or about 25.3 percent. Compression ratio = 300 / 224 = 1.34 (approximately).

For the theory part, compute the entropy H = - sum p log2 p for these probabilities. It comes out to about 2.22 bits per symbol, so Huffman's 2.24 is very close to the lower bound, and efficiency = H / L is about 99 percent. Examiners love that comparison line.

Encoding and decoding a word

Encode "face": f = 0, a = 1100, c = 100, e = 111, so the bit stream is 01100100111, 11 bits instead of 12 with fixed codes. Decoding reads bits until a complete code matches: 0 is f, 1100 is a, 100 is c, 111 is e. Because no code is a prefix of another, there is never any ambiguity.

Mistakes to avoid

  1. Not re-sorting. After round 2 the new node 25 must sit after 16, not at the front.
  2. Mixing left/right conventions halfway. Your codes can differ from a friend's if you swap 0 and 1 at some node, and both are correct as long as the code lengths match. State your convention.
  3. Forgetting units. Average length is in bits per symbol.
  4. Skipping the verification. Sum of (frequency x code length) must equal the total bits you report.

Practice

Try frequencies A 0.4, B 0.2, C 0.2, D 0.1, E 0.1. There are ties, so two different trees are possible. Compute the average length for both and notice it is the same. Then do timed practice with real exam questions from https://gtuhero.com/gtu-papers/data-compression, and move on to arithmetic coding and LZ family questions right after this.

Top comments (0)