'str'对象没有属性'比较'

时间:2016-03-29 01:48:51

标签: python binary-search-tree

实际上我多次得到这个错误,我不知道它来自哪里。 我的功能是计算bst中的总比较, 她是我的代码

def total(bst):
     s = Stack()
        total = 0
        s.push(bst._root)
        while not s.is_empty():
            x = s.pop()
            nu = x._value
            total = total + nu.comparisons
            if x._right:
                s.push(x._right)
            if node._left:
                s.push(x._left)

        return total

这是错误

total = total + i.comparisons
AttributeError: 'str' object has no attribute 'comparisons'

这是字母的claas:

class Letter:

    def __init__(self, letter):

        assert letter.isalpha() and letter.isupper(), "Invalid letter"

        self.letter = letter
        self.count = 0
        self.comparisons = 0
        return

    def __str__(self):

        return "{}: {}, {}".format(self.letter, self.count, self.comparisons)

    def __eq__(self, rs):

        self.count += 1
        self.comparisons += 1
        result = self.letter == rs.letter
        return result

    def __lt__(self, rs):

        self.comparisons += 1
        result = self.letter < rs.letter
        return result

    def __le__(self, rs):

        self.comparisons += 1
        result = self.letter <= rs.letter
        return result

任何人都可以向我解释,感谢任何healp。

1 个答案:

答案 0 :(得分:0)

i(或num)似乎是str,其中没有comparisons属性。但是你的Letter个对象呢。也许将其投放到Letter然后尝试使用comparisons,如下所示:Letter(i).comparisons

编辑:

为什么比较总是为空的原因是因为你从未将该变量与其他变量进行比较(这是比较增加的地方,请参阅__eq__中的Letter)。只有在您说出i=Letter(i)之类的内容时,它们才会开始更改,然后将ii == 1之类的内容进行比较。只有这样,你的比较才会增加。