我有建立哈夫曼树,其是如下的方法:类型错误:“<”不支持的“元组”的实例之间和“STR”
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
但同时I进料与以下参数的函数:
[(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()
。
'leastTwo'是元组的元组,然后用'combFreq'(一个整数)将它包装在* another *元组中。你不能将这个* inner *元组与其他每个元组的第二个元素中的字符串进行比较。 –
换句话说,您只能添加'(int,str)'元组,而不是'(int,((int,str),(int,str)))'元组。 –
现在,如果您只想对每个元组中的** first **值进行排序,则需要指定一个排序关键字来提取它。 –