高效算法——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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章