Kodewick
開始學 →
哈夫曼樹和哈夫曼編碼28 / 52

哈夫曼樹和哈夫曼編碼

第 28 課,共 52 課 · 第 5 部分 · 樹和堆 · 約 18 分鐘

哈夫曼樹是反覆把兩棵最輕的樹合併成一棵建出來的,每次用 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 壓縮,最後一步用的就是它。

每次合併兩個最小的

把每個字母看成一棵只有一個結點的樹,權值是它出現的次數。然後反覆做一件事:取出權值最小的兩棵樹,合併成一棵新樹,新根的權值是兩者之和,先取出的放左邊。只剩一棵樹時,它就是哈夫曼樹。

A 45
C 12
B 13
F 5
E 9
D 16

A 45、B 13、C 12、D 16、E 9、F 5:每次合併權值最小的兩棵樹,從下往上搭出整棵樹

「每次取出最小的兩個,再放回去一個」,正是上一課的堆:

main.py
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 誰大:

main.py
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,走過的路就是它的編碼。字母全在葉子上,所以沒有一個編碼是另一個的開頭(字首碼):讀到一個完整編碼時,就一定到了葉子,不會和別的字母混淆。

main.py
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
字母次數定長編碼哈夫曼編碼哈夫曼位數
A45000045 × 1 = 45
B1300110113 × 3 = 39
C1201010012 × 3 = 36
D1601111116 × 3 = 48
E910011019 × 4 = 36
F510111005 × 4 = 20
合計100300 位224 位
定長編碼每個字母 3 位,一共 300 位;哈夫曼編碼出現多的短、少的長,一共 224 位

解碼反過來:從根出發,讀到 0 往左、讀到 1 往右,一到葉子就輸出它的字母,再回到根接著讀。

100
A 45
55
25
C 12
B 13
30
14
F 5
E 9
D 16

解碼 1101:1 往右、1 往右、0 往左、1 往右,到了葉子 E。輸出 E,回到根讀下一個
單選

用這一關的編碼表(A 0、C 100、B 101、F 1100、E 1101、D 111),1100110100 解碼出來是什麼?

單選

哪一組編碼不是字首碼?

練習 1

從樹上讀出編碼

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')]
exercise1.py
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()))
輸出
點「執行」或按 Ctrl+Enter
練習 2

解碼

補全 decode(root, bits):從根出發,讀到 "0" 往左、"1" 往右;到了葉子就把字母放進結果,再回到根。樹是現成的:A 是 0,C 是 100,B 是 101,F 是 1100,E 是 1101,D 是 111。

要顯示
BEAC
ADDCAF
E
exercise2.py
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"))
輸出
點「執行」或按 Ctrl+Enter

帶權路徑長度

每個字母的編碼長度,就是它在樹裡的深度(離根幾步)。總位數 = 每個字母的次數 × 深度,加起來。這個數叫樹的帶權路徑長度(WPL,weighted path length)。哈夫曼樹就是讓 WPL 最小的那棵二元樹:越常用的字母放得越淺。

還有一個好算的辦法:每次合併時,兩棵子樹裡的所有字母都會深一層,總位數正好多出這兩棵樹的權值之和。所以 WPL = 所有合併出來的新結點的權值之和:14 + 25 + 30 + 55 + 100 = 224。

main.py
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 加計數的用法,以及「統計頻率 → 建樹 → 編碼 → 解碼」這一整條路:

main.py
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()))
單選

text 是 "aaaa",只有一種字母。如果 codes 不特判,a 的編碼是什麼?

小結

這一課帶走

哈夫曼:每次合併兩個最小的

  • 每個字母一棵樹,反覆合併權值最小的兩棵: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)))