代码跟踪和逻辑错误

时间:2015-10-05 09:41:11

标签: python python-3.x

class MyHashTable:

    def __init__(self, capacity):
        self.capacity = capacity
        self.slots = [None] * self.capacity

    def __str__(self):
        return str(self.slots )

    def __len__(self):
        count = 0
        for i in self.slots:
            if i != None:
                count += 1
        return count

    def hash_function(self, key):
        slot = key % len(self.slots)

        if key in self.slots:
            return slot

        elif (not key in self.slots) and len(self.slots) == self.capacity:
            return slot

        else:
            for i in self.slots:
                count = 0 
                if i == None:
                    return count
                count += 1

    def insert(self, key):
        print(len(self.slots)) #Why does this show an output of 2? 
        if key in self.slots:
            return -2

        elif (not key in self.slots) and (len(self.slots) != self.capacity): #Now this cant execute
            num = hash_function(key)
            self.slots[num] = key
            return num

        elif (not key in self.slots) and len(self.slots) == self.capacity:
            return -1

我想知道为什么上面的注释部分在insert(self, key) print语句中给出(2)而不是(0)。下面的elif语句不会执行,因为它给出(2)而不是(0)

的结果

的函数调用
x = MyHashTable(2)
print(len(x)) 

应该给:0

2 个答案:

答案 0 :(得分:1)

您正在初始化self.slots = [None] * self.capacity,因此对于capacity = 2self.slots[None, None],长度为2。

您的__len__方法无法运行,因为len(self.slot)拨打了self.slot.__len__,而不是self.__len__。如果您想使用覆盖方法,则应该改为调用len(self)

答案 1 :(得分:1)

如果您希望元素的长度不是None,则必须调用__len__函数(通过调用self.__len__())。对于列表,无有效条目。

顺便说一下。最好与a is Nonea is not None进行比较,而不是==!=