【问题标题】:Incrementing certain values in "Tuples" in Python在 Python 的“元组”中增加某些值
【发布时间】: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


【解决方案1】:

元组在 python 中是不可变的,这就是你不能更新值的原因。而且,这不是哈希表。哈希在 python 中被实现为字典。你可以用这个替换你的结构:

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

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

编辑:

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

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

【讨论】:

  • 这是我的大学想要的手动实现的“哈希表”。我们不允许使用内置函数,所以这只是为了理解哈希表。
  • 那你能把你已经有的代码贴出来吗?这样更容易提供帮助。
  • 我已将代码编辑到我的问题中,希望它已经足够了。请让我知道需要进行的任何更改。谢谢!
  • 我修改了答案以遵守您的限制。检查这是否是您要查找的内容。
  • 索引有一个小错误,应该是 self.array[position] = (position, self.array[position][1]+1) 但是,它仍然有效! !非常感谢,费尔南多!
猜你喜欢
  • 2016-03-23
  • 1970-01-01
  • 2020-11-05
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多