web-dev-qa-db-ja.com

TypeError:「Tuple」と「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
_

しかし、私は次のパラメータを関数に与えています:

_[(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()にあることがわかりました。

8
rhazkoomar

_(priority, (node, node))_形式で内部ノードを作成しているため、エラーがスローされます。等しい優先順位の場合、Pythonは、リーフノード(したがって_(priority, symbol)_ノードタプルの2番目の要素)からのシンボルを内部からの_(node, 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'
_

ハフマンツリーを構築するために、ノードの配列を並べ替える場合は、残りのタプル(シンボルまたは子ノード)を無視して、実際に優先順位のみで並べ替える必要があります。

_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')))))
_

個人的には、代わりに優先度キューを使用して、毎回ソートすることを避けます。 Pythonで優先度キューを実装する方法? を参照してください

8
Martijn Pieters