【问题标题】:String hashing with quadratic probing, in Python在 Python 中使用二次探测的字符串散列
【发布时间】: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


【解决方案1】:

在不了解 hashString() 函数的内部工作原理的情况下,我假设您正在获取一个字符串并将其转换为给定长度的哈希值。如果这是真的,那么您的 else 语句会设置一个超出您的 hashTable 范围的值(同样,这只是一个猜测,因为您没有给出 hashTable 的任何内部工作原理)。

发生这种情况的原因是,当您:

slot = slot + (collisions**2)%len(hashTable)

按照设计,散列通常是给定的长度,而您只是让它变长,因此超出了hashTable 的范围。

您需要修改整个新插槽以防止其超出范围。

slot = (slot + (collisions**2))%len(hashTable)

【讨论】:

  • 很高兴为您提供帮助。如果有效,您能否将答案设为正确?谢谢!
猜你喜欢
  • 2011-01-08
  • 2011-01-21
  • 2018-07-03
  • 2021-04-25
  • 2016-05-14
  • 2013-06-27
  • 2013-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多