TypeError:“<"在'tuple'和'str'实例之间不支持
我有一种构建霍夫曼树的方法,如下所示:
I have a method that build huffman tree which is as follows:
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
但是当我使用以下参数输入函数时:
but while I feed the function with following parameter:
[(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()
中.
While debugging I found the error was in tuples.sort()
.
抛出该错误是因为您以(priority, (node, node))
形式创建内部节点.为了获得相同的优先级,Python然后尝试将叶子节点(因此(priority, symbol)
节点元组中的第二个元素)中的符号与内部节点的(node, node)
元组进行比较:
The error is thrown because you are creating inner nodes in (priority, (node, node))
form. For equal priorities, Python then tries to compare a symbol from a leaf node (so the second element in a (priority, symbol)
node tuple) with the (node, node)
tuple from an inner 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'
要构建霍夫曼树,如果要对节点数组进行排序,则只需要按优先级排序,而忽略其余的元组(符号或子节点):
For building a huffman tree, if you want to sort your array of nodes, you only really need to sort on the priority, ignoring the rest of the tuples (symbols or child nodes):
tuples.sort(key=lambda t: t[0])
进行此更正后,您的buildTree()
函数将生成一棵树:
With that correction, your buildTree()
function produces a tree:
>>> 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')))))
就我个人而言,我将使用优先级队列,以避免每次都进行排序.请参阅如何在Python中实现优先级队列?
Personally, I'd use a priority queue instead, avoiding sorting each time. See How to implement Priority Queues in Python?