Python,了解Huffman代码2

时间:2015-12-18 21:29:49

标签: python huffman-code

我一直试图通过Rosetta code

来理解用Python编写的霍夫曼代码

我理解其中的大部分内容并对某些部分发表了评论:

from heapq import heappush, heappop, heapify 
from collections import defaultdict
import collections

txt = "abbaac!ccc" #txt is variable for string which will be encoded
symb2freq = collections.Counter(txt) #counts letter frequency
                                     #and puts in dictionary

def encode(symb2freq): #define a function

    heap = [[freq, [symbol, ""]] for symbol, freq in symb2freq.items()] #converts dictionary to a list in order to sort out alphabets in terms of frequencies

    heapify(heap) #This sorts out the list so that 1st element is always the
                  #smallest

    while len(heap) > 1:#while there is more than 1 element in the list

        left = heappop(heap) #Takes the lowest frequency from the list

        print("lo=", left)

        right = heappop(heap) #Takes the lowest frequency from the list        

        for x in left[1:]: 
            x[1] = '0' + x[1]
        for x in right[1:]:
            x[1] = '1' + x[1]
        add_freq= [left[0] + right[0]] + left[1:] + right[1:] #adds the frequencies and inserts frequency, symbol and alphabet (0 or 1) into one list e.g. [3, ['!', '0'], ['b', '1']]

        heappush(heap, add_freq )#inserts add_freq into heap

    return sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p)) #What is this doing?

huff = encode(symb2freq)
print ("Symbol\tWeight\tHuffman Code")
for p in huff:
    print ("%s\t%s\t%s" % (p[0], symb2freq[p[0]], p[1]))

有一行我不明白:

return sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p)) #What is this doing?

我已经改变了一点以便更好地理解。

1 个答案:

答案 0 :(得分:0)

堆在while循环之后只剩下一个元素。

heappop(heap)应该为你提供最后一个元素。

heappop(heap)[1:]获取最后一个堆元素的整个列表并删除第一个元素,我不知道为什么。

然后这个列表按sorted排序(...,key = lambda p:(len(p [-1]),p)) 这意味着此列表中的顺序将根据key中定义的函数重新排列。此函数按元素的长度或自身元素对列表进行排序。这应该命令你的霍夫曼代码从最短到最长。

因此,这一行基本上对生成的代码进行了排序。