2016-03-18 49 views
0

我想在Python中編寫一個函數,它會將字符串添加到哈希表中,並且在不導入數學的情況下使用二次探測解決任何衝突。在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:列表索引超出範圍,我敢肯定問題出在else塊不過,我似乎無法找到它的解決方案。任何幫助表示感謝,謝謝。

+2

什麼是散列串? –

+0

發生異常的線是什麼? –

+0

你在哪裏得到IndexError?我看到你做的唯一索引是'hashTable [slot]'。 – acdr

回答

0

不知道你的hashString()函數的內部工作,我假設你正在接受一個字符串並將其轉換爲給定長度的散列。如果這是真的,你的else語句就會設置一個超出你的hashTable範圍的值(再次,因爲你沒有給出你的hashTable的內部工作方式,所以只是一個猜測)。

爲什麼發生這種情況的原因是因爲你實際上做比界限slot較大,當你:

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

在設計上,散列通常是一個給定的長度,你只是使它不再,因此出於您的hashTable的界限。

您需要修改整個新插槽以防止出界。

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

+0

我明白你的意思了,謝謝! –

+0

很高興幫助。如果有效,你能否回答正確?謝謝! –