我正在创建一个哈希函数,并且对于将大小加倍,重新运行值,然后继续使用新表感到困惑。我所做的就是创建一个单独的数组来存储密钥,这样我就可以重新编写它(因为self.table存储了密钥和值)但是当我运行它时,它创建了新表但是散列了价值最终没有发生。有人有主意吗?
class Hashing(object):
def __init__(self,size):
self.array_size = size
self.table = self.array_size * [None]
self.size = 0
self.keyList = []
def _hash(self,key):
pos = key
print key, " ", pos % self.array_size
return pos % self.array_size
def doubleSize(self):
self.array_size = self.array_size*2
self.table = (self.array_size) * [None]
doubleHash = Hashing(self.array_size)
i = 0
for each in self.keyList:
print "Each ", each
doubleHash[each] = i
i += 1
print "double", self.table
def __setitem__(self,key,value):
if self.size > self.array_size/2:
self.doubleSize()
pos = self._hash(key)
while True:
if self.table[pos] is not None:
if self.table[pos][0] == key:
self.table[pos] = (key,value)
return
else:
self.table[pos] = (key,value)
self.keyList.append(key)
self.size += 1
return
pos = (pos + 1) % self.array_size
和main(因为缺少Python的更好的词......)
from Hashing import Hashing
myHash = Hashing(4)
i = 0
myArray = [1,12,13,11]
for each in myArray:
myHash[each] = i
i += 1
答案 0 :(得分:0)
问题的根源来自这一行:doubleHash = Hashing(self.array_size)
。
当你应该改变self中的值时,你正在创建一个全新的Hashing
对象。当doubleHash
超出范围时,doubleSize
方法的末尾将丢弃doubleHash
对象。