【发布时间】:2016-07-05 08:21:44
【问题描述】:
我正在尝试用 Python 编写一个函数,该函数将向哈希表添加字符串并通过二次探测解决任何冲突,而无需导入数学。
def addString(string, hashTable):
collisions = 0
stop = False
slot = (hashString(string, len(hashTable)))
while not stop:
if hashTable[slot] == None:
hashTable[slot] = string
stop = True
else:
slot = slot + (collisions**2)%len(hashTable)
collisions = collisions + 1
print('collisions: ', collisions)
我的问题是我不断收到 IndexError: list index out of range 并且我确定问题出在 else 块中,但是我似乎无法找到解决方案。任何帮助表示赞赏,谢谢。
【问题讨论】:
-
异常发生在哪一行?
-
您从哪里得到 IndexError?我看到你做的唯一索引是
hashTable[slot]。 -
hashString 是一个将字符串作为参数并返回哈希值的函数。带有 if 语句的行会出现错误。
标签: python hashtable quadratic-probing