The cost of a code
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
Huffman builds a code tree from the bottom up, rarest letters first. Each letter starts as a one-node tree in a priority queue keyed by its count (lines 3 and 4). heapify makes a min-heap, so heappop always returns the smallest count.
Pop the two smallest counts, f 5 and e 9 (lines 6, 7). Join them under a new node of count 14 and push it back (lines 8, 9). Every f and e now needs one more bit: the bit total grows by 14.
Repeat. The smallest two are now c 12 and b 13: they join under 25, which goes back in the queue. The bit total grows by 25, to 39. Greedy never looks ahead: it only asks which two counts are smallest right now.
Now the smallest are the new node 14 and d 16. A whole tree is popped just like a letter: 14 and d join under 30, so f and e sink one level deeper. Bit total: 39 + 30 = 69.
25 and 30 join under 55. Notice that a, with 45, has waited the whole time: the most common letter is merged last, so it will sit nearest the root with the shortest code. Bit total: 69 + 55 = 124.
Last pair: a 45 and 55 make the root, count 100, the whole file. One tree is left, so the loop stops and line 10 returns it. Six letters took 5 merges, each a few O(log n) heap steps: O(n log n) in all.
Codes, cost and proof
From the root, left is 0 and right is 1. e is right, right, left, right: 1101. Likewise a = 0, c = 100, b = 101, d = 111, f = 1100. Letters sit only at leaves, so no code starts another.
Cost = sum of count × length: 45·1 + 13·3 + 12·3 + 16·3 + 9·4 + 5·4 = 224 bits, 25% fewer than 300. That equals 14 + 25 + 30 + 55 + 100: a merge adds a bit per letter below it.
Exchange argument: some best tree has the two rarest letters as deepest siblings; swapping them down never raises the cost. Merging them into one letter of count 14 cuts every cost by 14, so a best smaller tree gives a best tree. Induction ends it.
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.