香农,费诺和赫夫曼编码代码
时间: 2023-06-10 22:08:14 浏览: 128
以下是Python实现的三种编码算法:香农编码、费诺编码和赫夫曼编码。
## 香农编码
```python
def shannon_fano(p):
if len(p) == 1:
return {p.keys()[0]: '0'}
s = sum(p.values())
m = s / 2
left, right = {}, {}
for k, v in p.items():
if m >= s:
left[k] = v
else:
right[k] = v
s -= v
code = shannon_fano(left)
code.update(shannon_fano(right))
for k in left:
code[k] = '0' + code[k]
for k in right:
code[k] = '1' + code[k]
return code
```
## 费诺编码
```python
def huffman(p):
heap = [[w, [s, '']] for s, w in p.items()]
heapq.heapify(heap)
while len(heap) > 1:
lo = heapq.heappop(heap)
hi = heapq.heappop(heap)
for pair in lo[1:]:
pair[1] = '0' + pair[1]
for pair in hi[1:]:
pair[1] = '1' + pair[1]
heapq.heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])
return dict(sorted(heapq.heappop(heap)[1:], key=lambda p: p[0]))
```
## 赫夫曼编码
```python
def huffman(p):
heap = [[w, [s, '']] for s, w in p.items()]
heapq.heapify(heap)
while len(heap) > 1:
lo = heapq.heappop(heap)
hi = heapq.heappop(heap)
for pair in lo[1:]:
pair[1] = '0' + pair[1]
for pair in hi[1:]:
pair[1] = '1' + pair[1]
heapq.heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])
return dict(sorted(heapq.heappop(heap)[1:], key=lambda p: p[0]))
```
这些实现都需要一个字典,其中键是字符,值是相应字符的频率。例如,如果要编码字符串“hello world”,则字典应如下所示:
```python
p = {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
```
阅读全文