check = set()
for i in range(len(names)):
    count = 0
    for j in range( len(names)):
        if names[i] == names[j]:
            count +=1
        my_tup = (names[j], count)
        check.add(my_tup)
print(check)

this code doesn"t give the correct output which is as follows: {('m', 2), ('m', 1), ('b', 1), ('p', 3), ('b', 0), ('p', 2), ('b', 3), ('m', 0), ('m', 3), ('b', 2), ('p', 1)}

names = ["b", "b", "b", "m", "p", "p", "m"]
    #made the set so that I can record the frequencies of each word only once,
     #since it doesn't allow repetation
    check = set() 
    for i in names:
    #tuple, because it's hashable
        my_tup = (i, names.count(i))
        check.add(my_tup)
    
    print(check)

This code gives the correct output, which is as follows: {('m', 2), ('p', 2), ('b', 3)}

1

There are 1 best solutions below

0
On

Use Counter for this job.

from collections import Counter 
print(Counter(["b", "b", "b", "m", "p", "p", "m"]))