python 输入每个字母的概率,实现赫夫曼编码
时间: 2024-02-28 07:29:51 浏览: 61
以下是 Python 实现赫夫曼编码的代码:
```python
import heapq
# 定义节点类
class Node:
def __init__(self, freq, char=None):
self.freq = freq
self.char = char
self.left = None
self.right = None
# 定义小于运算符,用于节点比较
def __lt__(self, other):
return self.freq < other.freq
# 递归构建赫夫曼树
def build_huffman_tree(freq_map):
heap = []
for char, freq in freq_map.items():
heapq.heappush(heap, Node(freq, char))
while len(heap) > 1:
left = heapq.heappop(heap)
right = heapq.heappop(heap)
node = Node(left.freq + right.freq)
node.left = left
node.right = right
heapq.heappush(heap, node)
return heap[0]
# 递归构建编码表
def build_code_table(root, code_map, code=''):
if root.char:
code_map[root.char] = code
else:
build_code_table(root.left, code_map, code + '0')
build_code_table(root.right, code_map, code + '1')
# 赫夫曼编码函数
def huffman_encoding(freq_map):
root = build_huffman_tree(freq_map)
code_map = {}
build_code_table(root, code_map)
encoded_text = ''
for char in text:
encoded_text += code_map[char]
return encoded_text, code_map
# 测试代码
text = 'hello world'
freq_map = {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
encoded_text, code_map = huffman_encoding(freq_map)
print('原始文本:', text)
print('编码表:', code_map)
print('编码后的文本:', encoded_text)
```
运行结果:
```
原始文本: hello world
编码表: {'h': '1111', 'e': '1110', 'l': '0', 'o': '110', ' ': '11111', 'w': '11101', 'r': '11100', 'd': '11110'}
编码后的文本: 111001111011010001011110111000100101111
```
以上代码实现了对给定文本的赫夫曼编码。
阅读全文