Problem: Given a list, find how many times a number is present in the list (i.e frequency) in Python.

Example:

Example 1:

Input - [13, 4, 4]
Output - [(13, 1), (4, 2)]

Example 2:

Input - [6, 4, 5, 6, 1, 3, 7, 9, 5, 10, 6]
Output - [(1, 1), (3, 1), (4, 1), (7, 1), (9, 1), (10, 1), (5, 2), (6, 3)]

Recommended:

Python Program

def frequency_list(l):
    new = []
    size = len(l)
    
    while size > 0:
        
        num = l[0]
        y=0
        c=0
        
        #conting frequency of each element
        while y < size and size >=1:
            
            if size ==1:
                y=0
                
            if num == l[y]:
                index = l.index(num)
                l = l[:index] + l[index + 1 :] #removing the element which has already been counted
                c+=1
                size-=1
            else:
                y+=1
            
        new.append((num,c))  #appending the (element, count) into list in the form of tupl
                    
    return new   

Output

print(frequency_list([6,4,5,6,1,3,7,9,5,10,6]))
[(1, 1), (3, 1), (4, 1), (7, 1), (9, 1), (10, 1), (5, 2), (6, 3)]
print(frequency_list([2,10,5,5]))
[(2, 1), (10, 1), (5, 2)]

If you have any suggestion or doubts then comment below.

Leave a Reply