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
'''
霍夫曼编码
最新推荐文章于 2023-12-14 09:17:11 发布