高效算法——06哈夫曼编码(Python)

06哈夫曼编码

 

复杂度: O(nlogn)

算法: 

#coding=utf-8
"""
    算法:哈夫曼编码
    作者:lph-China
    时间:2019/7/15
"""

def huffman(freq):

   h = []
   for a in freq:
       heappush(h, (freq[a], a))
   while len(h) > 1:
       (fl, l) = heappop(h)
       (fr, r) = heappop(h)
       heappush(h, (fl + fr, [1, r]))
   code = {}
   extract(code, h[0][1])
   return code

def extract(code, tree, prefix = ""):
    if isinstance(tree, list):
        l, r = tree
        extract(code, l, prefix + "0")
        extract(code, r, prefix + "1")
    else:
        code[tree] = prefix

 

你可能感兴趣的:(高效算法)