Python – Find the frequency of numbers greater than each element in a list
Given a list, a new list is constructed that has frequency of elements greater than or equal to it, corresponding to each element of the list.
Input : test_list = [6, 3, 7, 1, 2, 4]
Output : [2, 4, 1, 6, 5, 3]
Explanation : 6, 7 are greater or equal to 6 in list, hence 2.
Input : test_list = [6, 3, 7]
Output : [2, 3, 1]
Explanation : 6, 7 are greater or equal to 6 in list, hence 2.
Method 1 : Using sum() and list comprehension
Here, nested list comprehension is used to access each element of the list and sum() is used to get summation of elements which are greater than or equal to the indexed element.
Python3
# initializing list test_list = [ 6 , 3 , 7 , 1 , 2 , 4 ] # printing original list print ( "The original list is : " + str (test_list)) # sum() performs counts of element which are Greater or equal to res = [ sum ( 1 for ele in test_list if sub < = ele) for sub in test_list] # printing result print ( "Greater elements Frequency list : " + str (res)) |
Output:
The original list is : [6, 3, 7, 1, 2, 4]
Greater elements Frequency list : [2, 4, 1, 6, 5, 3]
Method 2 : Using sorted(), bisect_left() and list comprehension
In this, we get elements smaller than the element using bisect_left(). Then, subtracting the number so obtained from total length gives us count of elements greater than element.
Python3
# import module import bisect # initializing list test_list = [ 6 , 3 , 7 , 1 , 2 , 4 ] # printing original list print ( "The original list is : " + str (test_list)) # sorting before bisect temp = sorted (test_list) # getting total greater elements for each element res = [ len (test_list) - bisect.bisect_left(temp, ele) for ele in test_list] # printing result print ( "Greater elements Frequency list : " + str (res)) |
Output:
The original list is : [6, 3, 7, 1, 2, 4]
Greater elements Frequency list : [2, 4, 1, 6, 5, 3]