Home > Enterprise >  Counting equal values(collision) in python dict
Counting equal values(collision) in python dict

Time:09-24

This post was not useful to me post_link

So i am asking here:

i have a python dict:

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

And I have this code

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

That returns the unicode of a string, for exemple:

get_index(teste, 'Andres') 

returns [605]

What a I want to to is tho pass my dict an for every key,value the code calculates de unicode_sum of the each string and append it to collisions:

I tried:

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)

What I want to get as result is:

get_index(a)

output: [605, 402, 605]

Then i can calculate the number of collision by just doing len(collision) - set(collision)

CodePudding user response:

Since "Andres" can't be present in your dictionary twice, I'll scramble the letters of the other instance to show that you'll get both results of 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

This will also work for a list of strings, a tuple of strings, and a set of strings (where a set will also not allow you to have more than one "Andres").

  • Related