霍夫曼编码

from heapq import heappush, heappop, heapify
from collections import defaultdict
 
def HuffmanEncode(characterFrequency):
    """Huffman encode the given dict mapping symbols to weights"""
    heap = [[freq, [sym, ""]] for sym, freq in list(characterFrequency.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:])
    return sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p))


inputText = "this is an example for huffman encoding"
characterFrequency = defaultdict(int)
for character in inputText:
    characterFrequency[character] += 1

huffCodes = HuffmanEncode(characterFrequency)
print("Symbol\tFrequency\tHuffman Code")
for p in huffCodes:
    print("%s\t\t\t%s\t\t\t%s" % (p[0], characterFrequency[p[0]], p[1]))
'''
Symbol	Frequency	Huffman Code
 			6			101
n			4			010
a			3			1001
e			3			1100
f			3			1101
h			2			0001
i			3			1110
m			2			0010
o			2			0011
s			2			0111
g			1			00000
l			1			00001
p			1			01100
r			1			01101
t			1			10000
u			1			10001
x			1			11110
c			1			111110
d			1			111111
'''


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值