【问题标题】:Counting equal values(collision) in python dict在python dict中计算相等的值(碰撞)
【发布时间】:2022-04-09 06:15:05
【问题描述】:

这篇文章对我没有用post_link

所以我在这里问:

我有一个 python 字典:

a = {'Andres':234,'Paul':345,'Andres':675}

我有这个代码

def get_index(dict, a_string):
    # Variable to store the result (updated after each iteration)
    result = 0
    #Variable to append the final result of each key in the dict
    collisions =[]
    
    for a_character in a_string:
        # Convert the character to a number (using ord)
        a_number = ord(a_character)
        # Update result by adding the number
        result += a_number
    collisions.append(result)
    
    # Take the remainder of the result with the size of the data list
    list_index = result % len(data_list)
    return collisions

返回字符串的unicode,例如:

get_index(teste, 'Andres') 

returns [605]

我想要的是为每个键传递我的 dict ,值代码计算每个字符串的 de unicode_sum 并将其附加到冲突中:

我试过了:

def get_index(dict):
    for k,v in teste.items:
          for a_character in a_string:
            # Convert the character to a number (using ord)
            a_number = ord(a_character)
            # Update result by adding the number
            result += a_number
        collisions.append(result)

我想要得到的结果是:

get_index(a)

output: [605, 402, 605]

然后我可以通过len(collision) - set(collision)来计算碰撞次数

【问题讨论】:

  • 查找collections.Counter。它可能会让你的任务变得更容易。
  • Python 不会让你拥有字典 {'Andres':234, 'Paul':345, 'Andres':675}。你实际拥有的是{'Andres':675, 'Paul':345}。
  • 这也不是计算碰撞的可靠方法。序数之和为 605 的字符串不止一个。
  • 如果您尝试将相同的键添加到字典中,当 Python 只是要覆盖任何现有键的值时,您为什么要“计算”冲突也不是很清楚。
  • @ddejohn 我明白你的意思。我把 Andres 放了两次只是为了得到相同的 ord() 结果!我试图让它变得简单,就像在我的哈希函数中一样(我不会使用 python dict)我会允许这种情况发生。

标签: python python-3.x


【解决方案1】:

由于"Andres" 不能在您的字典中出现两次,我将打乱另一个实例的字母以表明您将获得605 的两个结果:

>>> d = {"Andres": 234, "Paul": 345, "nAsedr": 675}
>>> collisions = [sum(map(ord, s)) for s in d]
>>> collisions
[605, 402, 605]
>>> len(collisions) - len(set(collisions))
1

这也适用于list 字符串、tuple 字符串和set 字符串(其中set 也不允许您拥有多个"Andres")。

【讨论】:

猜你喜欢
  • 2011-06-19
  • 2012-07-23
  • 2017-08-24
  • 1970-01-01
  • 2014-03-02
  • 2011-04-12
  • 1970-01-01
  • 1970-01-01
  • 2019-04-30
相关资源
最近更新 更多