我有一个构建 Huffman 树的方法,如下所示:
def buildTree(tuples) :
while len(tuples) > 1 :
leastTwo = tuple(tuples[0:2]) # get the 2 to combine
theRest = tuples[2:] # all the others
combFreq = leastTwo[0][0] + leastTwo[1][0] #enter code here the branch points freq
tuples = theRest + [(combFreq,leastTwo)] # add branch point to the end
tuples.sort() # sort it into place
return tuples[0] # Return the single tree inside the list
但是当我用以下参数喂函数时:
[(1, 'b'), (1, 'd'), (1, 'g'), (2, 'c'), (2, 'f'), (3, 'a'), (5, 'e')]
我得到的错误为
File "<stdin>", line 7, in buildTree
tuples.sort()
TypeError: '<' not supported between instances of 'tuple' and 'str'
调试时,我发现错误是在tuples.sort()
。
由于您正在以(priority, (node, node))
形式创建内部节点,因此会引发错误。对于相同的优先级,Python 会尝试将叶节点中的符号(因此(priority, symbol)
节点元组中的第二个元素)与内部节点中的(node, node)
元组进行比较:
>>> inner = (combFreq, leastTwo)
>>> inner
(2, ((1, 'b'), (1, 'd')))
>>> theRest[1]
(2, 'c')
>>> theRest[1] < inner
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'tuple'
对于构建霍夫曼树,如果要对节点数组进行排序,则只需要按优先级排序,而忽略其余的元组(符号或子节点):
tuples.sort(key=lambda t: t[0])
通过这个修正,你的buildTree()
函数产生了一个树:
>>> buildTree([(1, 'b'), (1, 'd'), (1, 'g'), (2, 'c'), (2, 'f'), (3, 'a'), (5, 'e')])
(15, ((6, ((3, 'a'), (3, ((1, 'g'), (2, 'c'))))), (9, ((4, ((2, 'f'), (2, ((1, 'b'), (1, 'd'))))), (5, 'e')))))
就个人而言,我会使用优先级队列,避免每次排序。请参阅How to implement Priority Queues in Python?
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(80条)