python代码实现哈夫曼编码
时间: 2023-10-13 16:21:56 浏览: 88
哈夫曼编码python实现
5星 · 资源好评率100%
好的,我可以回答这个问题。以下是Python代码实现哈夫曼编码的示例:
```python
from heapq import heappush, heappop, heapify
from collections import defaultdict
def encode(symb2freq):
heap = [[freq, [symb, ""]] for symb, freq in symb2freq.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))
# Example usage:
txt = "this is an example for huffman encoding"
symb2freq = defaultdict(int)
for char in txt:
symb2freq[char] += 1
huff = encode(symb2freq)
print("Symbol\tWeight\tHuffman Code")
for p in huff:
print("%s\t%s\t%s" % (p[0], symb2freq[p[0]], p[1]))
```
这个代码使用了默认字典来计算每个字符的频率,然后使用堆来构建哈夫曼树,并编码每个字符。
阅读全文