在 Python 中"Tuples"递增某些值



有没有办法为每个不同的碰撞增加一个值?

例如,我有一个哈希表 [(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 开始的情况下做到这一点。

元组在python中是不可变的,这就是为什么你不能更新这个值。而且,这不是哈希表。哈希在python中实现为字典。您可以通过以下方式替换您的结构:

d = {1234: 1, 5678: 5, 2145: 7}

然后,您可以执行诸如d[1234] += 1之类的操作来增加值。

编辑:

为了符合不使用内置类型的限制,您实际上需要创建一个新的元组,因为它们是不可变的。但是您应该使用元组中的先前值。它应该看起来像这样:

 self.array[position] = (position, self.array[position][1]+1)

最新更新