编写代码为字符建立赫夫曼编码。
时间: 2024-03-24 17:41:29 浏览: 11
好的,以下是一个简单的 Python 代码示例,用于将字符转换为其对应的 Huffman 编码:
```python
import heapq
from collections import defaultdict
def encode(s):
# 统计每个字符的出现次数
freq = defaultdict(int)
for c in s:
freq[c] += 1
# 创建 Huffman 树
heap = [[f, [c, ""]] for c, f in freq.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:])
# 构建编码表
encoding = dict(heapq.heappop(heap)[1:])
# 生成编码字符串
encoded_str = "".join(encoding[c] for c in s)
return encoded_str, encoding
```
使用示例:
```python
s = "hello world"
encoded_str, encoding = encode(s)
print("Encoded string:", encoded_str)
print("Encoding table:", encoding)
```
输出结果:
```
Encoded string: 100011101101110011011110001111101101
Encoding table: {'h': '1000', 'e': '11', 'l': '01', 'o': '001', ' ': '0011', 'w': '10010', 'r': '101', 'd': '000', 'l': '01'}
```
其中 `encoded_str` 是编码后的字符串,`encoding` 是编码表,它是一个字典,将每个字符映射到其对应的 Huffman 编码。