首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python,了解Huffman代码2

Python,了解Huffman代码2
EN

Stack Overflow用户
提问于 2015-12-19 05:29:49
回答 1查看 337关注 0票数 0

我一直在尝试理解Rosetta code用Python编写的霍夫曼代码

我理解了它的大部分,并对其中的一些部分进行了评论:

代码语言:javascript
复制
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]))

有一句话我不明白:

代码语言:javascript
复制
return sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p)) #What is this doing?

为了更好地理解,我对它做了一些更改。

EN

回答 1

Stack Overflow用户

发布于 2015-12-19 06:41:24

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

heappop(heap)应该会得到最后一个元素。

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

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

所以这行代码基本上是对生成的代码进行排序。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34364216

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档