huffmandict源代码
时间: 2023-07-25 18:29:57 浏览: 46
以下是Python实现的Huffman编码的huffmandict函数的源代码:
```python
from heapq import heappush, heappop, heapify
from collections import defaultdict
from typing import Dict, Tuple
def huffmandict(freq: Dict[str, int]) -> Tuple[Dict[str, str], int]:
"""
Given a dictionary of character frequencies, return a dictionary
of Huffman codes, and the length of the encoded message.
"""
heap = [[wt, [sym, ""]] for sym, wt in freq.items()]
heapify(heap)
while len(heap) > 1:
lo = heappop(heap)
hi = heappop(heap)
for pair in lo[1:]:
pair[1] = '0' + pair[1]
for pair in hi[1:]:
pair[1] = '1' + pair[1]
heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])
huffcode = dict(sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p)))
return huffcode, sum(freq[sym] * len(huffcode[sym]) for sym in freq)
```
这个函数接受一个字典,其中包含字符和它们的出现频率。它返回一个元组,其中包含一个字典,其中包含每个字符的Huffman编码,以及编码的总长度。
相关推荐
![application/octet-stream](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)