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

nested for loop not counting correctly (python)

I have two lists:

common_nodes_list = ['A', 'A', 'B', 'C', 'C', 'C']
uniquePatterns = ['A', 'B', 'C']

I am trying to create a dict with the counts of each unique pattern. Like this:

A: 2
B: 1
C: 3

I have a for loop inside of another for loop:

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

patternRank = {}

for i in common_nodes_list:
    score = 0
    for pattern in uniquePatterns:
        if pattern == i:
            score += 1   
    patternRank[pattern]=score

patternRank

but It’s only returning:

'C': 1

>Solution :

You should do it the other way: for each pattern in the unique patterns, count how many there are in the common_nodes_list:

common_nodes_list = ['A', 'A', 'B', 'C', 'C', 'C']
unique_patterns = ['A', 'B', 'C']

pattern_rank = {}

for pattern in unique_patterns:
    score = 0
    for node in common_nodes_list:
        if node == pattern:
            score += 1
    pattern_rank[pattern] = score

print(pattern_rank)
>> {'A': 2, 'B': 1, 'C': 3}

And maybe, try to be consistant with the way you name the variables: snake_case or CapWords.

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