Sub topic 2
Building the Huffman Tree with a Min-Heap
This chapter assumes you know Python, binary trees, min-heaps (heapq), and basic probability. It also assumes you have read the previous chapter, which covered prefix-free codes and code trees.
The Greedy Merge
Huffman's algorithm builds the code tree from the bottom up:
- Put every symbol in a min-heap, keyed by its frequency.
- Pop the two lowest-frequency nodes and merge them into a parent whose frequency is their sum.
- Push the parent back into the heap and repeat until one node is left. That node is the root.
Every left edge adds a 0 to a code and every right edge adds a 1. Rare symbols get merged early, so they end up deep in the tree with long codes.
import heapq
import math
from collections import Counter
from itertools import count
def build_codes(text):
freq = Counter(text)
tiebreak = count()
heap = [(f, next(tiebreak), sym) for sym, f in freq.items()]
heapq.heapify(heap)
if len(heap) == 1:
_, _, sym = heap[0]
return {sym: "0"}
while len(heap) > 1:
f1, _, left = heapq.heappop(heap)
f2, _, right = heapq.heappop(heap)
heapq.heappush(heap, (f1 + f2, next(tiebreak), (left, right)))
codes = {}
def walk(node, prefix):
if isinstance(node, tuple):
walk(node[0], prefix + "0")
walk(node[1], prefix + "1")
else:
codes[node] = prefix
walk(heap[0][2], "")
return codes
def encode(text, codes):
return "".join(codes[ch] for ch in text)
def decode(bits, codes):
reverse = {code: sym for sym, code in codes.items()}
out, current = [], ""
for b in bits:
current += b
if current in reverse:
out.append(reverse[current])
current = ""
return "".join(out)
def entropy_bits(text):
n = len(text)
return -sum((f / n) * math.log2(f / n) for f in Counter(text).values())
text = "abracadabra"
codes = build_codes(text)
bits = encode(text, codes)
assert decode(bits, codes) == text
print(codes)
print(bits, len(bits), "bits vs", 8 * len(text))
print(round(entropy_bits(text), 3), round(len(bits) / len(text), 3))Encoding a Message
To encode a message, replace each symbol with its code and join the results. The text abracadabra gives a=0, b=110, r=111, c=100, d=101, so it encodes to 23 bits. Plain 8-bit ASCII would need 88 bits.
Decoding the Bitstream
The decoder reads one bit at a time and stops as soon as the bits read so far match a code. That match is never ambiguous, because no code is a prefix of another code. A common mistake is to decode with a code table that is not prefix-free. The decoder then emits the wrong symbol early and every symbol after it comes out wrong.
Entropy: The Lower Bound
Shannon entropy H is the minimum average number of bits per symbol that any symbol-by-symbol code can achieve. The Huffman average length L always satisfies H ≤ L < H + 1. For abracadabra, H ≈ 2.04 bits and L ≈ 2.091 bits per symbol.
Exercise
Frequencies are x:4, y:2, z:1, w:1. What are the code lengths, and what is the total encoded length in bits?
Show answer
Merge z and w (2), merge that node with y (4), then merge it with x (8). The code lengths are x=1, y=2, z=3, w=3. The total is 4·1 + 2·2 + 1·3 + 1·3 = 14 bits.