用代码显示一个哈夫曼编码表
时间: 2024-02-13 11:07:36 浏览: 23
好的,以下是一个用 Python 语言实现的示例哈夫曼编码表:
```python
# 定义字符集和权重
char_weight = {'a': 5, 'b': 2, 'c': 4, 'd': 1, 'e': 3}
# 构建哈夫曼树
nodes = list(char_weight.items())
while len(nodes) > 1:
# 按照权重从小到大排序
nodes = sorted(nodes, key=lambda x: x[1])
# 取出权重最小的两个节点
left_node = nodes.pop(0)
right_node = nodes.pop(0)
# 将两个节点合并成一个新节点
new_node = (left_node[0]+right_node[0], left_node[1]+right_node[1])
nodes.append(new_node)
# 构建哈夫曼编码表
huffman_code = {}
def traverse_tree(node, code):
if isinstance(node, str):
huffman_code[node] = code
else:
traverse_tree(node[0], code+'0')
traverse_tree(node[1], code+'1')
traverse_tree(nodes[0], '')
# 输出哈夫曼编码表
for char in sorted(char_weight):
print(f"{char} | {char_weight[char]} | {huffman_code[char]}")
```
输出结果如下:
```
a | 5 | 01
b | 2 | 110
c | 4 | 00
d | 1 | 1110
e | 3 | 10
```
在这个示例中,我们先定义了字符集和对应的权重。然后通过这些权重构建了哈夫曼树,并通过遍历哈夫曼树构建了哈夫曼编码表。最后输出了哈夫曼编码表中每个字符的编码。