2017-01-28 42 views
3

我有建立哈夫曼树,其是如下的方法:类型错误:“<”不支持的“元组”的实例之间和“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()

+0

'leastTwo'是元组的元组,然后用'combFreq'(一个整数)将它包装在* another *元组中。你不能将这个* inner *元组与其他每个元组的第二个元素中的字符串进行比较。 –

+1

换句话说,您只能添加'(int,str)'元组,而不是'(int,((int,str),(int,str)))'元组。 –

+0

现在,如果您只想对每个元组中的** first **值进行排序,则需要指定一个排序关键字来提取它。 –

回答

3

由于您在(priority, (node, node))表单中创建内部节点,因此引发错误。对于相等的优先级,然后Python试图从叶节点与(node, node)元组的符号(所以在一(priority, symbol)节点元组中的第二元素)从内节点比较:

>>> 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?

+0

非常感谢Martijn Pieters。喜欢你的人让世界变得美丽。 – rhazkoomar

相关问题