我正在努力从树叶上造一棵哈夫曼树。我有我的分类名单,但不知道如何继续

2024-10-01 19:14:58 发布

您现在位置:Python中文网/ 问答频道 /正文

所以这个函数需要一个字符串,我用下面的代码让它创建一个元组列表[character,frequency]。我们没有使用可预测性,只是实际频率。有什么建议可以让我开始构建正确的树,使我可以向下遍历它来添加它的1和0?在

from operator import itemgetter, attrgetter, methodcaller
def code(msg):
# list of characters already counted
characters = []
# list of tuples
frequencies = []
# look through the message
for char in msg:
    if char not in characters:
        print(char)

        characters.append(char)
        thisCount = 0
        # if current character has already been added to list
        for chara in msg:
            if char == chara:
                # increase its count if another found
                thisCount = thisCount + 1
        # create its tuple
        tup = (char, thisCount)
        # add tuple to frequencies
        frequencies.append(tup)

# sort tuple list by element[1] numerically
sortedFreq = sorted(frequencies, key=lambda x: x[1])
print(sortedFreq)
make_Tree(sortedFreq)
return

Tags: ofinforifmsglistprintcharacter
1条回答
网友
1楼 · 发布于 2024-10-01 19:14:58

首先,熟悉处理这个应用程序的Python结构。一个基本字典可以比你的数组对做得更好,而计数器可以很快做到这一点:

from collections import Counter
freq = Counter(msg)

freq现在是一个字典的形式

^{pr2}$

代表“你好”的信息。现在,要获得元组的排序列表,只需从计数器获取元组并将其插入排序:

sortedFreq = sorted(freq.items(), key=lambda x: x[1])

现在开始施工。我不知道你设置了什么数据结构,但算法基本上是这样的:

while len(sortedFreq) > 1
    join the last two elements
    re-sort the tree

这能让你找到解决方案吗?在

相关问题 更多 >

    热门问题