python哈夫曼编码代码
时间: 2023-12-01 09:42:40 浏览: 79
以下是Python实现哈夫曼编码的代码:
```python
import heapq
from collections import defaultdict
def encode(symb2freq):
heap = [[wt, [sym, ""]] for sym, wt in symb2freq.items()]
heapq.heapify(heap)
while len(heap) > 1:
lo = heapq.heappop(heap)
hi = heapq.heappop(heap)
for pair in lo[1:]:
pair[1] = '0' + pair[1]
for pair in hi[1:]:
pair[1] = '1' + pair[1]
heapq.heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])
return sorted(heapq.heappop(heap)[1:], key=lambda p: (len(p[-1]), p))
txt = "hello world"
symb2freq = defaultdict(int)
for ch in txt:
symb2freq[ch] += 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]))
```
这段代码实现了哈夫曼编码的基本功能,包括构建哈夫曼树、生成哈夫曼编码等。在这个例子中,我们使用了一个字符串“hello world”作为输入,然后统计每个字符出现的频率,最后生成对应的哈夫曼编码。
阅读全文