【发布时间】:2017-03-09 06:04:33
【问题描述】:
class HashTable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] * self.size
def put(self,key,data):
hashvalue = self.hashfunction(key,len(self.slots))
if self.slots[hashvalue] == None:
self.slots[hashvalue] = key
self.data[hashvalue] = data
else:
if self.slots[hashvalue] == key:
self.data[hashvalue] = data #replace
else:
nextslot = self.rehash(hashvalue,len(self.slots))
while self.slots[nextslot] != None and \
self.slots[nextslot] != key:
nextslot = self.rehash(nextslot,len(self.slots))
if self.slots[nextslot] == None:
self.slots[nextslot]=key
self.data[nextslot]=data
else:
self.data[nextslot] = data #replace
我一直在阅读哈希表上的这一点数据结构,下面需要对此部分进行解释。
如果key已经存在,为什么要替换数据?
if self.slots[hashvalue] == key:
self.data[hashvalue] = data #replace
另外,有人能解释一下这部分吗? Nextslot 将是空插槽。 我们只是重新哈希,如果它不为空且密钥不存在,再次重新哈希?
nextslot = self.rehash(hashvalue,len(self.slots))
while self.slots[nextslot] != None and \
self.slots[nextslot] != key:
nextslot = self.rehash(nextslot,len(self.slots))
【问题讨论】:
-
请描述预期行为和观察到的行为之间的差异。最好给出示例输入和输出。