【发布时间】:2017-03-30 08:45:07
【问题描述】:
有没有办法为每次不同的碰撞增加一个值?
例如,我有一个哈希表 [(1234, 1), (5678, 5), (2145, 7)] 与 1234 发生冲突,我想将整个元组更新为 (1234, 2 )。我找到了一种方法,即初始化一个名为 val = 0 的变量,但问题是,它会从停止的地方递增。
def __init__(self, size):
self.val = 0
def __setitem__(self, key, value):
position = self.hash(key)
j = 1
for _ in range(self.table_size):
#if there is nothing there, self.array[position] = (position, value)
if self.array[position] is None:
self.array[position] = (position, value)
self.count += 1
return
elif self.array[position][0] == self.hash(key):
#if there is an exisiting key and key == position, increment self.val
self.val += 1
self.array[position] = (position, self.val)
self.collisions += 1
return
else:
#if there's an existing key and key != position, find next available slot
position = (position + j**2) % self.table_size
j += 1
self.collisions += 1
self.count += 1
基本上,我希望 self.val 回到它停止的位置以获取它自己的密钥,但我不知道如何在不重置它并使每个密钥再次从 0 开始的情况下做到这一点。
【问题讨论】:
-
元组是不可变的,您不能替换其中的值。您只能替换整个元组。
-
是的,对不起。我正是这个意思。我已经编辑了问题。
-
为什么不包括你的尝试代码,但它不起作用?用具体的代码帮助你要容易得多,即使它不起作用。将其设为minimal reproducible example,包含输入、预期输出和实际输出。
-
我已经编辑了我的代码,希望这就足够了。请让我知道我能做些什么来让它变得更好!谢谢!
标签: python-3.x hash hashtable