Program to find elements from list which have occurred at least k times in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of elements called nums, and a value k. We have to find those elements which have occurred at least k number of times.

So, if the input is like nums = [2,5,6,2,6,1,3,6,3,8,2,5,9,3,5,1] k = 3, then the output will be [2, 5, 6, 3]

To solve this, we will follow these steps −

  • c := a list containing frequencies of each elements present in nums
  • res := a new list
  • for each key n in c, do
    • if c[n] >= k, then
      • insert n at the end of res
  • return res


Let us see the following implementation to get better understanding −

from collections import Counter

def solve(nums, k):
   c = Counter(nums)
   res = []
   for n in c:
      if c[n] >= k:
   return res

nums = [2,5,6,2,6,1,3,6,3,8,2,5,9,3,5,1]
k = 3
print(solve(nums, k))


[2,5,6,2,6,1,3,6,3,8,2,5,9,3,5,1], 3


[2, 5, 6, 3]
Published on 12-Oct-2021 08:57:30