Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I absorb the values of dictionary based on their keys?

Here’s the question I’m trying to solve:

Given a dictionary, whose keys are binary strings, and values are numbers, for example: result = {'000': 25, '010': 34, '100':22, '101':35}, my goal is to first sort the keys with the same number of ‘bit flips’, then add up the associated values, and return them in an ascending order based on the number of flips. For example, in this case, the desired output could be [25,22,69] (0,1,and 2 flips).

I have the first part of my code, which is to transform the strings into the number of bit flips:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def count_flip(string):
    return len([x for x in range(1, len(string)) if string[x] != string[x-1]])

I’m stuck on the second part, which is to return the values with the order specified, given a dictionary input such as result. My thought is to loop through all the keys in the input dictionary, but I really don’t know how can I absorb the strings (keys) with the same number of flips, applying count_flip(string)?

>Solution :

collections.Counter should help.

from collections import Counter

flip_counts = Counter()
for binary_string, value in result.items():
    flip_counts[count_flip(binary_string)] += value
output = [v for _, v in sorted(flip_counts.items())]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading