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 - Element frequencies in percent range
When finding elements whose frequencies fall within a specific percentage range, we can use Python's Counter class along with percentage calculations to filter elements based on their occurrence rates.
Example
Below is a demonstration of finding elements with frequencies between 13% and 60% ?
from collections import Counter
my_list = [56, 34, 78, 90, 11, 23, 6, 56, 79, 90]
print("The list is :")
print(my_list)
start, end = 13, 60
my_freq = dict(Counter(my_list))
print("Element frequencies:", my_freq)
my_result = []
for element in set(my_list):
percent = (my_freq[element] / len(my_list)) * 100
print(f"Element {element}: {percent}%")
if percent >= start and percent <= end:
my_result.append(element)
print("The result is :")
print(my_result)
Output
The list is :
[56, 34, 78, 90, 11, 23, 6, 56, 79, 90]
Element frequencies: {56: 2, 34: 1, 78: 1, 90: 2, 11: 1, 23: 1, 6: 1, 79: 1}
Element 34: 10.0%
Element 6: 10.0%
Element 11: 10.0%
Element 78: 10.0%
Element 23: 10.0%
Element 79: 10.0%
Element 56: 20.0%
Element 90: 20.0%
The result is :
[56, 90]
How It Works
The algorithm follows these steps ?
Count frequencies:
Counter(my_list)creates a dictionary with element countsCalculate percentage: For each unique element, compute
(frequency / total_length) * 100Filter by range: Include elements whose percentage falls between start and end values
Return results: Only elements with frequencies between 13% and 60% are included
Alternative Approach Using List Comprehension
Here's a more concise version using list comprehension ?
from collections import Counter
my_list = [56, 34, 78, 90, 11, 23, 6, 56, 79, 90]
start, end = 13, 60
my_freq = Counter(my_list)
total = len(my_list)
result = [element for element in set(my_list)
if start <= (my_freq[element] / total) * 100 <= end]
print("Elements in percentage range:", result)
Elements in percentage range: [56, 90]
Conclusion
Use Counter to get element frequencies, then calculate percentages and filter by range. This technique is useful for data analysis when you need to identify elements with specific occurrence patterns.
