哈夫曼树和哈夫曼编码
哈夫曼树是反复把两棵最轻的树合并成一棵建出来的,每次用 heapq 取出最小的两个;常见的字母得到短编码、少见的得到长编码,往左记 0、往右记 1。
一段 100 个字母的文字只用到 A~F 六个字母。每个字母用 3 位二进制存(000 到 101),一共 300 位。可如果 A 出现了 45 次、F 只出现了 5 次,让 A 用 1 位、F 用 4 位,总数就能降到 224 位,省下四分之一。问题是:长短怎么分,总位数才最少,而且一串 0 和 1 读回来时还分得清每个字母在哪里断开?哈夫曼在 1952 年给出了答案。zip、gzip、PNG 里的 DEFLATE 压缩,最后一步用的就是它。
每次合并两个最小的
把每个字母看成一棵只有一个结点的树,权值是它出现的次数。然后反复做一件事:取出权值最小的两棵树,合并成一棵新树,新根的权值是两者之和,先取出的放左边。只剩一棵树时,它就是哈夫曼树。
「每次取出最小的两个,再放回去一个」,正是上一课的堆:
1import heapq2from itertools import count3 4class Node:5 def __init__(self, weight, ch=None, left=None, right=None):6 self.weight = weight7 self.ch = ch # 叶子才有字母8 self.left = left9 self.right = right10 11def huffman(freq):12 order = count() # 0, 1, 2, …:权值一样时比它13 h = [(w, next(order), Node(w, ch)) for ch, w in freq.items()]14 heapq.heapify(h)15 while len(h) > 1:16 w1, _, a = heapq.heappop(h) # 最小的17 w2, _, b = heapq.heappop(h) # 第二小的18 print("合并", w1, "+", w2, "=", w1 + w2)19 heapq.heappush(h, (w1 + w2, next(order), Node(w1 + w2, None, a, b)))20 return h[0][2]21 22freq = {"A": 45, "B": 13, "C": 12, "D": 16, "E": 9, "F": 5}23root = huffman(freq)24print(root.weight, root.left.ch, root.right.weight)
合并 5 + 9 = 14 合并 12 + 13 = 25 合并 14 + 16 = 30 合并 25 + 30 = 55 合并 45 + 55 = 100 100 A 55
6 个字母合并了 5 次:每次合并树的个数少 1,n 棵树要 n − 1 次。每次是两次 heappop 加一次 heappush,各 O(log n),建树一共 O(n log n)。
权值 2、3、4、7、8 搭哈夫曼树,第二次合并的是哪两个?
6 个字母搭出来的哈夫曼树,一共有几个结点?
结点比不了大小
堆里为什么放 (权值, 计数, 结点) 三样,而不是 (权值, 结点) 两样?元组比大小是从第一项开始比,第一项一样才比第二项。两个权值一样时,就要比两个 Node 对象,而 Python 不知道两个 Node 谁大:
1import heapq2 3class Node:4 def __init__(self, weight, ch=None, left=None, right=None):5 self.weight = weight6 self.ch = ch7 self.left = left8 self.right = right9 10h = []11try:12 for ch, w in [("A", 2), ("B", 1), ("C", 1)]:13 heapq.heappush(h, (w, Node(w, ch)))14 print("放进了", ch)15except TypeError as e:16 print(type(e).__name__ + ":B 和 C 都是 1,只好比两个 Node 对象")
放进了 A 放进了 B TypeError:B 和 C 都是 1,只好比两个 Node 对象
放 C 的时候,它的权值 1 和 B 一样,堆要比 (1, B 的结点) 和 (1, C 的结点),就报错了。中间加一个一直递增的计数,权值一样时比计数,计数永远不会一样,就不会比到结点。它还顺带让结果可重复:权值一样时,先放进去的先出来,每次运行建出的树都一样。
| 堆里放的 | 权值一样时 | 结果 |
|---|---|---|
(w, node) | 比两个结点 | TypeError |
(w, ch, node) | 比字母,可合并出来的树没有字母 | 新树也要编一个「名字」,容易出错 |
(w, next(order), node) | 比计数 | 永远比得出来,先放的先出 |
另一种办法是给 Node 写 __lt__(按权值比),但权值一样时谁先出来就说不清了,不如计数清楚。
堆里只放 (权值, 结点) 两样,什么时候会报 TypeError?
三个元组的中间一项是 count() 给的计数。打印什么?
1from itertools import count2 3order = count()4a = (5, next(order), "x")5b = (5, next(order), "y")6c = (3, next(order), "z")7print(a < b, c < a, a[1], c[1])
读出编码:往左 0,往右 1
从根走到每个字母,往左记 0、往右记 1,走过的路就是它的编码。字母全在叶子上,所以没有一个编码是另一个的开头(前缀码):读到一个完整编码时,就一定到了叶子,不会和别的字母混淆。
1import heapq2from itertools import count3 4class Node:5 def __init__(self, weight, ch=None, left=None, right=None):6 self.weight = weight7 self.ch = ch8 self.left = left9 self.right = right10 11def huffman(freq):12 order = count()13 h = [(w, next(order), Node(w, ch)) for ch, w in freq.items()]14 heapq.heapify(h)15 while len(h) > 1:16 w1, _, a = heapq.heappop(h)17 w2, _, b = heapq.heappop(h)18 heapq.heappush(h, (w1 + w2, next(order), Node(w1 + w2, None, a, b)))19 return h[0][2]20 21def codes(node, prefix, out):22 if node.ch is not None: # 叶子:走过的路就是编码23 out[node.ch] = prefix24 else:25 codes(node.left, prefix + "0", out)26 codes(node.right, prefix + "1", out)27 return out28 29freq = {"A": 45, "B": 13, "C": 12, "D": 16, "E": 9, "F": 5}30table = codes(huffman(freq), "", {})31for ch in sorted(table):32 print(ch, freq[ch], table[ch])
A 45 0 B 13 101 C 12 100 D 16 111 E 9 1101 F 5 1100
| 字母 | 次数 | 定长编码 | 哈夫曼编码 | 哈夫曼位数 |
|---|---|---|---|---|
| A | 45 | 000 | 0 | 45 × 1 = 45 |
| B | 13 | 001 | 101 | 13 × 3 = 39 |
| C | 12 | 010 | 100 | 12 × 3 = 36 |
| D | 16 | 011 | 111 | 16 × 3 = 48 |
| E | 9 | 100 | 1101 | 9 × 4 = 36 |
| F | 5 | 101 | 1100 | 5 × 4 = 20 |
| 合计 | 100 | 300 位 | 224 位 |
解码反过来:从根出发,读到 0 往左、读到 1 往右,一到叶子就输出它的字母,再回到根接着读。
用这一关的编码表(A 0、C 100、B 101、F 1100、E 1101、D 111),1100110100 解码出来是什么?
哪一组编码不是前缀码?
从树上读出编码
✓huffman 已经写好了。补全 codes(node, prefix, out):走到叶子时把 prefix 记成这个字母的编码;往左走在 prefix 后面加 "0",往右加 "1"。
[('A', '0'), ('B', '101'), ('C', '100'), ('D', '111'), ('E', '1101'), ('F', '1100')]
[('x', '10'), ('y', '11'), ('z', '0')]1import heapq2from itertools import count3 4class Node:5 def __init__(self, weight, ch=None, left=None, right=None):6 self.weight = weight7 self.ch = ch8 self.left = left9 self.right = right10 11def huffman(freq):12 order = count()13 h = [(w, next(order), Node(w, ch)) for ch, w in freq.items()]14 heapq.heapify(h)15 while len(h) > 1:16 w1, _, a = heapq.heappop(h)17 w2, _, b = heapq.heappop(h)18 heapq.heappush(h, (w1 + w2, next(order), Node(w1 + w2, None, a, b)))19 return h[0][2]20 21def codes(node, prefix, out):22 # 叶子(ch 不是 None):out[node.ch] = prefix;否则左边加 "0"、右边加 "1"23 return out24 25table = codes(huffman({"A": 45, "B": 13, "C": 12, "D": 16, "E": 9, "F": 5}), "", {})26print(sorted(table.items()))27table = codes(huffman({"x": 1, "y": 1, "z": 2}), "", {})28print(sorted(table.items()))
解码
✓补全 decode(root, bits):从根出发,读到 "0" 往左、"1" 往右;到了叶子就把字母放进结果,再回到根。树是现成的:A 是 0,C 是 100,B 是 101,F 是 1100,E 是 1101,D 是 111。
BEAC ADDCAF E
1class Node:2 def __init__(self, weight, ch=None, left=None, right=None):3 self.weight = weight4 self.ch = ch5 self.left = left6 self.right = right7 8L = lambda ch: Node(0, ch)9root = Node(100, None, L("A"),10 Node(55, None,11 Node(25, None, L("C"), L("B")),12 Node(30, None, Node(14, None, L("F"), L("E")), L("D"))))13 14def decode(root, bits):15 out, node = [], root16 # 每一位:0 往左,1 往右;node.ch 不是 None 就输出,node 回到 root17 return "".join(out)18 19print(decode(root, "10111010100"))20print(decode(root, "011111110001100"))21print(decode(root, "1101"))
带权路径长度
每个字母的编码长度,就是它在树里的深度(离根几步)。总位数 = 每个字母的次数 × 深度,加起来。这个数叫树的带权路径长度(WPL,weighted path length)。哈夫曼树就是让 WPL 最小的那棵二叉树:越常用的字母放得越浅。
还有一个好算的办法:每次合并时,两棵子树里的所有字母都会深一层,总位数正好多出这两棵树的权值之和。所以 WPL = 所有合并出来的新结点的权值之和:14 + 25 + 30 + 55 + 100 = 224。
1import heapq2 3freq = {"A": 45, "B": 13, "C": 12, "D": 16, "E": 9, "F": 5}4code = {"A": "0", "B": "101", "C": "100", "D": "111", "E": "1101", "F": "1100"}5print("次数 × 编码长度:", sum(freq[ch] * len(code[ch]) for ch in freq))6 7h = list(freq.values())8heapq.heapify(h)9merged = []10while len(h) > 1:11 w = heapq.heappop(h) + heapq.heappop(h)12 merged.append(w)13 heapq.heappush(h, w)14print("合并出来的权值:", merged, sum(merged))15print("定长 3 位:", 3 * sum(freq.values()))
次数 × 编码长度: 224 合并出来的权值: [14, 25, 30, 55, 100] 224 定长 3 位: 300
只要总位数,连树都不用建:堆里放数字就行。
四个字母出现 1、1、2、4 次。哈夫曼编码的总位数,和每个字母定长 2 位的总位数,各是多少?
1import heapq2 3h = [1, 1, 2, 4]4heapq.heapify(h)5cost = 06while len(h) > 1:7 w = heapq.heappop(h) + heapq.heappop(h)8 cost += w9 heapq.heappush(h, w)10print(cost, 2 * sum([1, 1, 2, 4]))
面试里: 哈夫曼是贪心算法的经典例子:每一步只管合并当前最小的两个,最后却是全局最优。常问的是「为什么是前缀码」(字母都在叶子上)、「建树的复杂度」(n − 1 次合并,每次 O(log n),共 O(n log n))、「哈夫曼树唯一吗」(不唯一:权值一样时谁左谁右可以换,但 WPL 总是同一个最小值)。
权值 2、3、4、7、8 的哈夫曼树,带权路径长度(WPL)是多少?
工作里这样写
工作里不会自己写哈夫曼压缩:要压缩数据,用标准库的 zlib、gzip、zipfile,它们的 DEFLATE 算法先找重复的片段,再用哈夫曼编码。自己写一遍的价值在于看清 heapq 加计数的用法,以及「统计频率 → 建树 → 编码 → 解码」这一整条路:
1import heapq2from collections import Counter3from itertools import count4 5class Node:6 def __init__(self, weight, ch=None, left=None, right=None):7 self.weight = weight8 self.ch = ch9 self.left = left10 self.right = right11 12def huffman(freq):13 order = count()14 h = [(w, next(order), Node(w, ch)) for ch, w in freq]15 heapq.heapify(h)16 while len(h) > 1:17 w1, _, a = heapq.heappop(h)18 w2, _, b = heapq.heappop(h)19 heapq.heappush(h, (w1 + w2, next(order), Node(w1 + w2, None, a, b)))20 return h[0][2]21 22def codes(node, prefix, out):23 if node.ch is not None:24 out[node.ch] = prefix or "0" # 只有一种字母时也要有 1 位25 else:26 codes(node.left, prefix + "0", out)27 codes(node.right, prefix + "1", out)28 return out29 30text = "abracadabra"31freq = sorted(Counter(text).items()) # 排好序:每次运行建出同一棵树32root = huffman(freq)33table = codes(root, "", {})34print(freq)35print(sorted(table.items()))36 37bits = "".join(table[ch] for ch in text)38print(bits, len(bits), "位;每个字母 8 位要", 8 * len(text), "位")39 40out, node = [], root41for b in bits: # 解码:0 往左,1 往右,到叶子就输出42 node = node.left if b == "0" else node.right43 if node.ch is not None:44 out.append(node.ch)45 node = root46print("".join(out) == text)
[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]
[('a', '0'), ('b', '110'), ('c', '100'), ('d', '101'), ('r', '111')]
01101110100010101101110 23 位;每个字母 8 位要 88 位
True
- 统计频率用
collections.Counter;为了每次结果一样,先sorted再建树。 - 堆里放
(权值, next(order), 结点):itertools.count()是现成的递增计数器。 - 只有一种字母时,树只有一个结点,编码是空串:要特判给它
"0"。 - 解码的结果要能还原,必须把编码表(或者各字母的次数)也存下来,真实的压缩格式都会把它写在数据前面。
建树之前,先用 Counter 数出每个字母出现几次。打印什么?
1from collections import Counter2 3print(sorted(Counter("banana").items()))
items() 给出 (字母, 次数) 的元组,sorted 按元组的第一项、也就是字母排:a、b、n。要按次数从多到少,用的是 most_common()。text 是 "aaaa",只有一种字母。如果 codes 不特判,a 的编码是什么?
"0",每个 a 占 1 位。小结
哈夫曼:每次合并两个最小的
- 每个字母一棵树,反复合并权值最小的两棵:n − 1 次,O(n log n)
- 堆里放 (权值, 计数, 结点):权值一样时比计数,不会去比结点
- 从根往左 0、往右 1,到叶子就是编码;字母都在叶子上,是前缀码
- 总位数 = 次数 × 深度之和 = 合并出来的权值之和,是所有二叉树里最小的
1h = [(w, next(order), Node(w, ch)) for ch, w in freq.items()]2heapq.heapify(h)3while len(h) > 1:4 w1, _, a = heapq.heappop(h); w2, _, b = heapq.heappop(h)5 heapq.heappush(h, (w1 + w2, next(order), Node(w1 + w2, None, a, b)))