Python | Elements with Frequency equal K

This is one of the most essential operation that programmer quite often comes in terms with. Be it development or competitive programming, this utility is quite essential to master as it helps to perform many tasks that involve this task to be its subtask. Lets discuss approach to achieve this operation.

Method #1 : Naive method
As the brute force method, we just count all the elements and then just return the elements whose count equals K. This is the basic method that one could think of executing when faced with this issue.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Elements with Frequency equal K
# using naive method
  
# initializing list
test_list = [9, 4, 5, 4, 4, 5, 9, 5]
  
# printing original list
print ("Original list : " + str(test_list))
  
# initializing K 
K = 3
  
# using naive method to 
# get most frequent element
res = []
for i in test_list:
    freq = test_list.count(i)
    if freq == K and i not in res:
        res.append(i)
      
# printing result
print ("Elements with count K are : " + str(res))

chevron_right


Output :

Original list : [9, 4, 5, 4, 4, 5, 9, 5]
Elements with count K are : [4, 5]
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.