我有一个构建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()
。
答案 0 :(得分:6)
因为您正在以$(window).scroll(function(){
var a = 112;
var pos = $(window).scrollTop();
if(pos > a) {
$("#compareHead").css({
position: 'fixed',
top: '51px'
});
}
});
形式创建内部节点而引发错误。对于相同的优先级,Python然后尝试将来自叶节点的符号(因此(priority, (node, node))
节点元组中的第二个元素)与来自内部节点的(priority, symbol)
元组进行比较:
(node, node)
为了构建一个huffman树,如果你想对你的节点数组进行排序,你只需要对优先级进行排序,忽略其余的元组(符号或子节点):
>>> 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()
就个人而言,我会使用优先级队列,每次都避免排序。见How to implement Priority Queues in Python?