2017-01-28 50 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

相關問題