0

I am trying to count the frequency of each digit as a single digit in a list. for example 1:5 times, 2: 4 times but i am not getting the individual count. Here is my code

def CountFrequency(my_list): 
    freq = {} 
    for item in my_list: 
        if (item in freq): 
            freq[item] += 1
        else: 
            freq[item] = 1
    for key, value in freq.items(): 
        print ("% d : % d"%(key, value)) 

my_list =[1, 21, 25, 53, 3, 14, 1, 12, 52, 33] 
print(CountFrequency(my_list))
ombk
  • 2,036
  • 1
  • 4
  • 16

3 Answers3

0

Intuition

Turn the items in your list to string, then check if the string is in the dictionary. Increase the count if it already exists.

def CountFrequency(my_list): 
    freq = {} 
    for item in my_list:
        for i in str(item):
            if (i in freq): 
                freq[i] += 1
            else: 
                freq[i] = 1
    for key, value in freq.items(): 
        print ("% d : % d"%(int(key), int(value))) 

my_list =[1, 21, 25, 53, 3, 14, 1, 12, 52, 33] 
CountFrequency(my_list)

#output
 1 :  5
 2 :  4
 5 :  3
 3 :  4
 4 :  1

To list

def CountFrequency(my_list): 
    freq = {} 
    list_1 = []
    for item in my_list:
        for i in str(item):
            if (i in freq): 
                freq[i] += 1
            else: 
                freq[i] = 1
    for key, value in freq.items(): 
        list_1.append((int(key), int(value)))
                      
    return list_1
                      
my_list =[1, 21, 25, 53, 3, 14, 1, 12, 52, 33] 
CountFrequency(my_list)

# output
[(1, 5), (2, 4), (5, 3), (3, 4), (4, 1)]

What I did is repetitive to avoid breaking your structure. freq.items() does the job directly of turning a dictionary to a list

ombk
  • 2,036
  • 1
  • 4
  • 16
0

One way is to convert the number to a string and iterate through the digits that way, converting them back to integers along the way.

def CountFrequency(my_list):
    freq = {}
    for item in my_list:
        for digit in str(item):
            digit = int(digit)
            if digit in freq:
                freq[digit] += 1
            else:
                freq[digit] = 1
    for key, value in freq.items():
        print ("% d : % d"%(key, value))

my_list =[1, 21, 25, 53, 3, 14, 1, 12, 52, 33]
CountFrequency(my_list)
big_bad_bison
  • 1,021
  • 1
  • 7
  • 12
0

Here is a solution without converting to strings

counter = {}

def count_digits(num):
    remainder = num % 10
    if remainder not in counter:
        counter[remainder] = 1
    else:
        counter[remainder] += 1
    num = num // 10
    if num == 0:
        return
    else:
        count_digits(num)

my_list = [1, 21, 25, 53, 3, 14, 1, 12, 52, 33]
for num in my_list: count_digits(num)

print(counter)
{1: 5, 2: 4, 5: 3, 3: 4, 4: 1}
kleerofski
  • 423
  • 4
  • 8