我是Python新手,目前我有一个哈希表类,通过线性探测解决冲突。但是,如果负载系数高于2/3,我想将数组的大小加倍。但是,我一直收到错误
if self.array[i]!=None:
IndexError: invalid index
是因为每次更改表格大小时,我的getLoadandAverageProbeLength
都不会更新尺寸吗?
我的设定项目功能:
def __setitem__(self, key, value):
position = self.hash_value(key)
sameKeyCollision=False
load,averageProbeLength= self.getLoadAndAverageProbeLength(self.totalProbeLength)
loadFactor=load
if loadFactor<(2/3):
if self.array[position] is None:#found empty slot, collision resolve
self.array[position] = (key, value)
self.count += 1
sameKeyCollision=False
return
elif self.array[position][0] == key:#found key
self.array[position] = (key, value)#update value, no collision
return
elif self.array[position][0] !=key and sameKeyCollision==False:#not found try next,first time collision
position = (position+1) % self.table_size
self.totalProbeLength+=1
self.collision+=1
sameKeyCollision=True
elif self.array[position][0] !=key and sameKeyCollision==True:#probing
position = (position+1) % self.table_size
self.totalProbeLength+=1
我的getLoadAndAverageProbeLength
def getLoadAndAverageProbeLength(self,probeLength):
count=0
averageProbeLength=0
for i in range(self.table_size):
if self.array[i]!=None:
count+=1
load= count/self.table_size
if count!=0:
averageProbeLength=probeLength/count
return load,averageProbeLength
这是我的哈希表的类构造函数:
def __init__(self, size=2):
self.count = 0
self.table_size = size
self.array = build_array(self.table_size)
self.collision=0
self.totalProbeLength=0
这是我的追溯:
Traceback (most recent call last):
File "C:\Users\User\Desktop\Assignment3Task3(b).py", line 18, in <module>
main()
File "C:\Users\User\Desktop\Assignment3Task3(b).py", line 15, in main
readFile(filename)
File "C:\Users\User\Desktop\Assignment3Task3(b).py", line 10, in readFile
hashTable[line]=line
File "C:\Users\User\Desktop\Assignment3Task4.py", line 55, in __setitem__
self.__setitem__(key,value)
File "C:\Users\User\Desktop\Assignment3Task4.py", line 29, in __setitem__
load,averageProbeLength= self.getLoadAndAverageProbeLength(self.totalProbeLength)
File "C:\Users\User\Desktop\Assignment3Task4.py", line 83, in getLoadAndAverageProbeLength
if self.array[i]!=None:
IndexError:索引无效