Sub topic 10
Canonical Huffman Codes
This chapter assumes you can build a Huffman tree with a min-heap and read codes off it. You should also be comfortable with Python's bit shifts (<<) and with binary formatting.
The problem with tree-derived codes
Huffman's algorithm fixes the length of each symbol's code. It does not fix the bits themselves. Swap the left and right children of any internal node and every code below that node changes, but no code gets longer or shorter. Ties in the heap cause the same thing: two correct implementations can produce different, equally optimal codes for the same input.
The variation becomes a problem when the decoder has to rebuild the code. Sending the whole tree, or every symbol's full bit pattern, costs space. A canonical Huffman code avoids this. It is a fixed rule that turns code lengths into code bits, so the encoder and decoder only need to agree on the lengths.
The canonical rule
Given each symbol's code length:
- Sort symbols by code length, then by symbol value to break ties.
- Give the first symbol the code 0, written with as many bits as its length.
- For each later symbol, add 1 to the previous code. If the length increased, shift left by the difference, which appends zeros.
Within one length, the codes are consecutive binary numbers. Each longer code starts just past the last shorter code, extended with zeros, so no shorter code can be a prefix of it.
Implementation
def canonical_codes(lengths):
# lengths: dict mapping symbol -> code length in bits
ordered = sorted(lengths.items(), key=lambda item: (item[1], item[0]))
codes = {}
code = 0
prev_len = ordered[0][1]
for sym, length in ordered:
code <<= (length - prev_len)
codes[sym] = format(code, "0{}b".format(length))
code += 1
prev_len = length
return codes
print(canonical_codes({"a": 1, "b": 2, "c": 3, "d": 3}))
# {'a': '0', 'b': '10', 'c': '110', 'd': '111'}Here is the trace for that input:
| Symbol | Length | Shift | Code value | Code |
|---|---|---|---|---|
| a | 1 | 0 | 0 | 0 |
| b | 2 | 1 | 2 | 10 |
| c | 3 | 1 | 6 | 110 |
| d | 3 | 0 | 7 | 111 |
To use it with the tree builder from earlier chapters, take {sym: len(code) for sym, code in build_codes(text).items()} and pass that dictionary to canonical_codes. The codes you get keep the same lengths, so the compressed size does not change.
Common errors
- Sorting by symbol before length. The rule only works when shorter codes come first.
- Sorting symbols in a different order from the decoder. Both sides must use the same order, usually the symbols' numeric values.
- Shifting before the first assignment using the wrong starting length.
prev_lenhas to start at the first symbol's length, or the first code gets padded with extra zeros.
Exercise
Compute the canonical codes for the lengths {"a": 2, "b": 2, "c": 2, "d": 3, "e": 3}, and check that they form a prefix-free code.
Show answer
a = 00, b = 01, c = 10, d = 110, e = 111. The three 2-bit codes are consecutive. Then the counter reaches 3 and shifts to 6 (110) for d, and d plus 1 gives 7 (111) for e. Neither 3-bit code starts with 00, 01, or 10, so no code is a prefix of another. The Kraft sum is 3/4 + 2/8 = 1.
Exercise
Why does a canonical code let a decompressor rebuild the code from lengths alone, when an ordinary Huffman tree does not?
Show answer
An ordinary tree's bit patterns depend on how ties were broken and which child became left or right, and the lengths do not record those choices. The canonical rule computes the bits from the sorted lengths alone, so any program that knows the lengths and the sort order gets the same codes.