gpt4 book ai didi

python - 代码追踪和逻辑错误

转载 作者:行者123 更新时间:2023-12-01 04:27:05 26 4
gpt4 key购买 nike

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) 打印语句中的注释部分给出 (2) 而不是 (0)。下面的 elif 语句不会执行,因为它给出的结果是 (2) 而不是 (0)

函数调用

x = MyHashTable(2)
print(len(x))

应给出:0

最佳答案

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

您的 __len__ 方法未运行,因为 len(self.slot) 调用 self.slot.__len__,而不是 self .__len__。如果您想使用重写方法,则应该调用 len(self)

关于python - 代码追踪和逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32945441/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com