2、编写一个程序,构造哈夫曼树和哈夫曼编码,要求输出建立的哈夫曼树和相关的哈夫曼编码python和代码演示
时间: 2023-06-10 16:03:35 浏览: 216
好的,非常感谢您的提问。下面是使用 Python 编写的构造哈夫曼树和编码的示例代码。
``` python
from heapq import heappush, heappop, heapify
from collections import defaultdict
# 构造哈夫曼树
def huffman_tree(freq):
heap = [[weight, [symbol, ""]] for symbol, weight in freq.items()]
heapify(heap)
while len(heap) > 1:
lo = heappop(heap)
hi = heappop(heap)
for pair in lo[1:]:
pair[1] = '0' + pair[1]
for pair in hi[1:]:
pair[1] = '1' + pair[1]
heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])
return sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p))
# 构造哈夫曼编码
def huffman_encoding(freq):
code = {}
for char, weight in freq.items():
code[char] = ""
tree = huffman_tree(freq)
for pair in tree:
code[pair[0]] = pair[1]
return code
# 示例
if __name__ == "__main__":
message = "hello world"
freq = defaultdict(int)
for symbol in message:
freq[symbol] += 1
code = huffman_encoding(freq)
print("哈夫曼编码表:\n", code)
encoded = "".join([code[symbol] for symbol in message])
print("编码后的消息:\n", encoded)
decoded = ""
char_code = ""
for bit in encoded:
char_code += bit
if char_code in code.values():
decoded += list(code.keys())[list(code.values()).index(char_code)]
char_code = ""
print("解码后的消息:\n", decoded)
```
以上代码可以成功地构造哈夫曼树和哈夫曼编码,并输出相关信息。需要注意的是,示例中是使用默认字典 `defaultdict(int)` 来统计字符出现的频率。您可以将 `freq` 参数替换成任何可以表示字符频率的数据结构。
阅读全文