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
Python program to print Rows where all its Elements' frequency is greater than K
When working with nested lists (2D arrays), you may need to filter rows where every element appears more than K times within that row. Python provides an elegant solution using the all() function combined with list comprehension.
Understanding the Problem
We want to find rows where each element's frequency within that specific row exceeds a threshold value K. For example, in row [11, 11, 11, 11], the element 11 appears 4 times, so its frequency is 4.
Solution Using Custom Function
Here's a complete program that defines a helper function to check frequency conditions ?
def frequency_greater_K(row, K):
return all(row.count(element) > K for element in row)
my_list = [[11, 11, 32, 43, 12, 23], [42, 14, 55, 62, 16], [11, 11, 11, 11], [42, 54, 61, 18]]
print("The list is:")
print(my_list)
K = 1
print(f"The value of K is: {K}")
my_result = [row for row in my_list if frequency_greater_K(row, K)]
print("Rows where all elements' frequency > K:")
print(my_result)
The list is: [[11, 11, 32, 43, 12, 23], [42, 14, 55, 62, 16], [11, 11, 11, 11], [42, 54, 61, 18]] The value of K is: 1 Rows where all elements' frequency > K: [[11, 11, 11, 11]]
How It Works
The frequency_greater_K() function uses two key components:
-
row.count(element)- counts occurrences of each element in the row -
all()- returns True only if all elements satisfy the condition
Let's trace through each row:
-
[11, 11, 32, 43, 12, 23]: Element 32 appears 1 time (not > 1), so False -
[42, 14, 55, 62, 16]: All elements appear 1 time each (not > 1), so False -
[11, 11, 11, 11]: Element 11 appears 4 times (4 > 1), so True -
[42, 54, 61, 18]: All elements appear 1 time each (not > 1), so False
Alternative Approach Using Collections
For better performance with larger datasets, use Counter ?
from collections import Counter
def frequency_greater_K_optimized(row, K):
freq = Counter(row)
return all(count > K for count in freq.values())
my_list = [[11, 11, 32, 43, 12, 23], [11, 11, 11, 11], [5, 5, 5, 6, 6, 6]]
K = 2
result = [row for row in my_list if frequency_greater_K_optimized(row, K)]
print("Optimized result:")
print(result)
Optimized result: [[11, 11, 11, 11], [5, 5, 5, 6, 6, 6]]
Conclusion
Use the all() function with list comprehension to filter rows based on element frequency. The Counter approach is more efficient for larger datasets as it counts each element only once.
