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
-
Economics & Finance
Selected Reading
Program to find elements from list which have occurred at least k times in Python
Sometimes we need to find elements from a list that appear a certain number of times or more. Python provides several approaches to solve this problem using frequency counting techniques.
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]
Using Counter from collections
The Counter class provides an efficient way to count element frequencies ?
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))
[2, 5, 6, 3]
Using Dictionary for Manual Counting
We can manually count frequencies using a dictionary ?
def solve_manual(nums, k):
freq = {}
# Count frequencies
for num in nums:
freq[num] = freq.get(num, 0) + 1
# Find elements with frequency >= k
result = []
for num, count in freq.items():
if count >= k:
result.append(num)
return result
nums = [2,5,6,2,6,1,3,6,3,8,2,5,9,3,5,1]
k = 3
print(solve_manual(nums, k))
[2, 5, 6, 3]
Using List Comprehension
A more concise approach using list comprehension with Counter ?
from collections import Counter
def solve_compact(nums, k):
c = Counter(nums)
return [num for num, count in c.items() if count >= k]
nums = [2,5,6,2,6,1,3,6,3,8,2,5,9,3,5,1]
k = 3
print(solve_compact(nums, k))
[2, 5, 6, 3]
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Counter | O(n) | O(n) | Readable and efficient |
| Manual Dictionary | O(n) | O(n) | No imports needed |
| List Comprehension | O(n) | O(n) | Concise one-liner |
Conclusion
Use Counter for the most readable solution. All methods have O(n) time complexity and effectively solve the frequency counting problem. Choose based on your preference for readability versus conciseness.
Advertisements
