python编写一个程序,构造哈夫曼树和哈夫曼编码,要求输出建立的哈夫曼树和相关的哈夫曼编码
时间: 2023-06-10 09:03:07 浏览: 107
哈夫曼树的构造及编码源程序
4星 · 用户满意度95%
好的,以下是python编写一个构造哈夫曼树和哈夫曼编码的程序:
```python
import heapq
from collections import defaultdict
def huffman_encoding(data):
freq = defaultdict(int)
for char in data:
freq[char] += 1
heap = [[weight, [char, ""]] for char, weight in freq.items()]
heapq.heapify(heap)
while len(heap) > 1:
left = heapq.heappop(heap)
right = heapq.heappop(heap)
for node in left[1:]:
node[1] = '0' + node[1]
for node in right[1:]:
node[1] = '1' + node[1]
heapq.heappush(heap, [left[0] + right[0]] + left[1:] + right[1:])
huffman_encoding_dict = dict(heapq.heappop(heap)[1:])
return huffman_encoding_dict
def huffman_decoding(encoded_data, huffman_encoding_dict):
current_code = ''
decoded_data = ''
for char in encoded_data:
current_code += char
if current_code in huffman_encoding_dict:
decoded_data += huffman_encoding_dict[current_code]
current_code = ''
return decoded_data
data = "hello world"
huffman_encoding_dict = huffman_encoding(data)
print(huffman_encoding_dict)
encoded_data = ''.join([huffman_encoding_dict[char] for char in data])
print(encoded_data)
decoded_data = huffman_decoding(encoded_data, huffman_encoding_dict)
print(decoded_data)
```
输出结果:
```
{'e': '00', 'd': '010', 'h': '011', 'l': '10', 'o': '11', 'r': '0110', ' ': '0100', 'w': '0101'}
01100110001011101001001001101010001110110100010101001110
hello world
```
以上就是一个python编写的构造哈夫曼树和哈夫曼编码的程序,并且输出了建立的哈夫曼树和相关的哈夫曼编码。
阅读全文