Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Program to find elements from list which have occurred at least k times in Python
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
- if c[n] >= k, then
- return res
Example
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: res.append(n) 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))
Input
[2,5,6,2,6,1,3,6,3,8,2,5,9,3,5,1], 3
Output
[2, 5, 6, 3]
Advertisements
