TypeError:'tuple'和'str'的实例之间不支持'<'

rha*_*mar 8 python sorting python-3.x

我有一个构建霍夫曼树的方法,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

但是我用以下参数提供函数:

[(1, 'b'), (1, 'd'), (1, 'g'), (2, 'c'), (2, 'f'), (3, 'a'), (5, 'e')]
Run Code Online (Sandbox Code Playgroud)

我得到的错误是

  File "<stdin>", line 7, in buildTree
    tuples.sort()
TypeError: '<' not supported between instances of 'tuple' and 'str'
Run Code Online (Sandbox Code Playgroud)

在调试时我发现了错误tuples.sort().

Mar*_*ers 8

抛出错误是因为您正在创建(priority, (node, node))表单中的内部节点.对于相同的优先级,Python然后尝试将来自叶节点的符号(因此(priority, symbol)节点元组中的第二个元素)与(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'
Run Code Online (Sandbox Code Playgroud)

对于构建霍夫曼树,如果要对节点数组进行排序,则只需要对优先级进行排序,忽略其余的元组(符号或子节点):

tuples.sort(key=lambda t: t[0])
Run Code Online (Sandbox Code Playgroud)

通过该更正,您的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')))))
Run Code Online (Sandbox Code Playgroud)

就个人而言,我会使用优先级队列,每次都避免排序.请参阅如何在Python中实现优先级队列?

  • 非常感谢Martijn Pieters。像您这样的人使世界变得美丽。 (3认同)