首页 > 解决方案 > 在python dict中计算相等的值(碰撞)

问题描述

这篇文章对我没有用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)

标签: python-3.x

解决方案


由于"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

这也适用于 a listof strings、a tupleof strings 和 a setof strings(其中 aset也不允许您拥有多个"Andres")。


推荐阅读