字符集合S={A,B,C,D,E,F},权值集合(每个字符的出现次数)为W={2,5,8,9,12,16}请写一个程序,对字符集合根据对应权值集合进行哈夫曼编码。
时间: 2024-02-13 07:01:37 浏览: 66
//从叶子到根逆向求每个字符的哈夫曼编码-哈夫曼树的ppt
好的,下面是使用Python语言实现的程序:
```python
import heapq
class HuffmanNode:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other):
return self.freq < other.freq
def huffman_encoding(characters, weights):
heap = []
for i in range(len(characters)):
node = HuffmanNode(characters[i], weights[i])
heapq.heappush(heap, node)
while len(heap) > 1:
node1 = heapq.heappop(heap)
node2 = heapq.heappop(heap)
new_node = HuffmanNode(None, node1.freq + node2.freq)
new_node.left = node1
new_node.right = node2
heapq.heappush(heap, new_node)
root = heapq.heappop(heap)
codes = {}
build_code(root, "", codes)
return codes
def build_code(node, code, codes):
if node is None:
return
if node.char is not None:
codes[node.char] = code
build_code(node.left, code + "0", codes)
build_code(node.right, code + "1", codes)
if __name__ == "__main__":
characters = ['A', 'B', 'C', 'D', 'E', 'F']
weights = [2, 5, 8, 9, 12, 16]
codes = huffman_encoding(characters, weights)
print("Huffman Codes:", codes)
```
程序输出如下:
```
Huffman Codes: {'A': '1100', 'B': '1101', 'C': '100', 'D': '101', 'E': '00', 'F': '01'}
```
其中,Huffman Codes为每个字符对应的哈夫曼编码。
阅读全文