Sub topic 1
Why Fixed-Length Codes Waste Bits
Prerequisites
This chapter assumes you know binary numbers and bits, basic Python, binary trees, and simple probability, meaning frequencies and proportions.
Fixed-Length vs Variable-Length Codes
A fixed-length code gives every symbol the same number of bits. ASCII uses 8 bits per character. If an alphabet has k symbols, a fixed-length code needs at least ceil(log2 k) bits per symbol.
Take the text abracadabra. It uses 5 distinct symbols, so a fixed-length code needs 3 bits each, or 33 bits for all 11 characters. The waste comes from treating a the same as d, even though a appears five times and d appears once. A variable-length code gives frequent symbols short codes and rare symbols long ones.
Counting Symbols: Frequencies and Probabilities
A symbol's frequency is how many times it occurs in the text. Its probability is that frequency divided by the length of the text.
from collections import Counter
text = "abracadabra"
freq = Counter(text)
n = len(text)
for sym, f in freq.most_common():
print(sym, f, round(f / n, 3))The output shows a with probability 0.455, b and r with 0.182 each, and c and d with 0.091 each.
Prefix-Free Codes and Unambiguous Decoding
Variable-length codes cause a problem: the decoder has to know where each code ends. Take the code a=0, b=01, c=1. The bits 01 could mean b or ac. This is the most common mistake when people design codes by hand.
A code is prefix-free when no code is the start of another code. With a prefix-free code, the decoder reads bits until they match a code, and the match cannot be confused with anything else. You don't need separators between codes.
def is_prefix_free(codes):
words = sorted(codes.values())
return all(not b.startswith(a) for a, b in zip(words, words[1:]))
good = {"a": "0", "b": "10", "r": "110", "c": "1110", "d": "1111"}
bad = {"a": "0", "b": "01", "c": "1"}
print(is_prefix_free(good), is_prefix_free(bad)) # True FalseThe good code encodes abracadabra in 5·1 + 2·2 + 2·3 + 1·4 + 1·4 = 23 bits, compared with 33 bits for the fixed-length code.
Representing Codes as Binary Trees
You can draw any binary code as a tree. A left edge means 0 and a right edge means 1. A code is prefix-free exactly when every symbol sits at a leaf. If a symbol sat on an internal node, its code would be a prefix of every code below it.
To decode, start at the root and follow one edge per bit. When you reach a leaf, output its symbol and go back to the root.
Exercise
Is the code {w: 0, x: 10, y: 110, z: 11} prefix-free? How many bits would a fixed-length code need per symbol for these four symbols?
Show answer
No. The code for z, 11, is a prefix of the code for y, 110, so z sits on an internal node of the tree. A fixed-length code for four symbols needs log2(4) = 2 bits per symbol.