1from heapq import *2def huffman(freq):3 q = list(freq)4 heapify(q)5 while len(q) > 1:6 x = heappop(q)7 y = heappop(q)8 w = x[0] + y[0]9 heappush(q, (w, x, y))10 return q[0]010010111001101111a:45c:12b:13f:5e:9d:16011401250130015501100#1#2#3#4#5#6fixed300Huffman
Letter blocks: each letter and its count; nodes: the sum of the two trees belowQueue: the trees waiting, smallest count firstA flying token: one heappop or heappushHuffman's greedy loop on the CLRS example: pop the two smallest counts from the priority queue, join them under a new node whose count is their sum, push it back. The tree grows upward one merge at a time; reading left = 0 and right = 1 from the root gives a prefix-free code. Each merge adds its count to the bit total: 14 + 25 + 30 + 55 + 100 = 224 bits, against 300 for a 3-bit code.

The cost of a code

  1. A file of 100 letters uses only a to f: a 45 times, b 13, c 12, d 16, e 9, f 5. A fixed-length code gives each letter 3 bits (2³ = 8 codes cover 6): 300 bits. Can common letters get shorter codes?

Merge the two smallest

Codes, cost and proof

What happens

;; step 1/10 · fixed-length
letter  count  fixed code
   a      45     000
   b      13     001
   c      12     010
   d      16     011
   e       9     100
   f       5     101
total 100 letters × 3 bits = 300 bits

The queue is drawn in pop order to make it easy to read. heapq really stores a binary heap, which is only partly sorted, but heappop always returns the smallest item. heapify runs in linear time and each push or pop in O(log n), so n letters cost O(n log n). The code card relies on all counts in the queue being different. With a tie, Python compares the second items of two tuples, and a letter against a tree raises TypeError. The heapq docs suggest a counter as a tie-breaker: (count, next(tick), tree). Ties also mean several optimal trees exist, all with the same cost.