How to find elements that appear more than list_size/K times in a list with Python

1 Answer

0 votes
def elements_that_appear_more_than_x_times(lst, k):
    size = len(lst)
    times = size // k
    
    print("more than", times, "times");
 
    freqency = {}
 
    for i in range(size):
        if lst[i] in freqency:
            freqency[lst[i]] += 1
        else:
            freqency[lst[i]] = 1
    
    return freqency

 

lst = [4, 8, 6, 5, 5, 8, 3, 2, 1, 2, 2, 5, 5, 5, 5, 8, 9, 8, 8]
k = 4
     
freqency = elements_that_appear_more_than_x_times(lst, k)

for i in freqency:
    if (freqency[i] > len(lst) // k):
        print(i)
        


'''
run

more than 4 times
8
5

'''

 



answered Feb 10, 2024 by avibootz
...