Python – Element frequencies in percent range
Last Updated :
08 Mar, 2023
Given a list of elements, and percent ranges, the task is to write a python program to extract all the elements whose frequency is present in a given range.
Input : test_list = [4, 6, 2, 4, 6, 7, 8, 4, 9, 1, 4, 6, 7, 8], strt, end = 13, 25
Output : [6, 7, 8]
Explanation : 21.4, 14.2, 14.2 is percentage presence of 6, 7, 8 respectively.
Input : test_list = [4, 6, 2, 4, 6, 7, 8, 4, 9, 1, 4, 6, 7, 8], strt, end = 13, 20
Output : [7, 8]
Explanation : 14.2, 14.2 is percentage presence of 7, 8 respectively.
Presence percentage can be simply computed by the below formula:
Frequency of the element present in the list/ total no. of elements in the list
Method #1 : Using Counter() + set() + loop + len()
In this, frequencies of all the elements are extracted using loop. Next step is to get the set of elements of list and check if frequencies are between range specified.
Python3
from collections import Counter
test_list = [ 4 , 6 , 2 , 4 , 6 , 7 , 8 , 4 , 9 , 1 , 4 , 6 , 7 , 8 ]
print ( "The original list is : " + str (test_list))
strt, end = 13 , 25
freqs = dict (Counter(test_list))
res = []
for ele in set (test_list):
percent = (freqs[ele] / len (test_list)) * 100
if percent > = strt and percent < = end:
res.append(ele)
print ( "Elements within range of frequencies : " + str (res))
|
Output:
The original list is : [4, 6, 2, 4, 6, 7, 8, 4, 9, 1, 4, 6, 7, 8]
Elements within range of frequencies : [6, 7, 8]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using Counter() + loop + len()
This performs tasks in an almost similar manner, the key difference being the Counter keys are iterated rather than the list elements, as they’d provide similar output.
Python3
from collections import Counter
test_list = [ 4 , 6 , 2 , 4 , 6 , 7 , 8 , 4 , 9 , 1 , 4 , 6 , 7 , 8 ]
print ( "The original list is : " + str (test_list))
strt, end = 13 , 25
freqs = dict (Counter(test_list))
res = []
for ele in freqs:
percent = (freqs[ele] / len (test_list)) * 100
if percent > = strt and percent < = end:
res.append(ele)
print ( "Elements within range of frequencies : " + str (res))
|
Output:
The original list is : [4, 6, 2, 4, 6, 7, 8, 4, 9, 1, 4, 6, 7, 8]
Elements within range of frequencies : [6, 7, 8]
Time complexity: O(n*n), where n is the length of the test_list. The Counter() + loop + len() takes O(n*n) time
Auxiliary Space: O(n), extra space of size n is required
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...