Python – Find the frequency of numbers greater than each element in a list
Last Updated :
20 Mar, 2023
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
test_list = [ 6 , 3 , 7 , 1 , 2 , 4 ]
print ( "The original list is : " + str (test_list))
res = [ sum ( 1 for ele in test_list if sub < = ele) for sub in test_list]
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]
Time Complexity: O(n), where n is the length of the input list. This is because we’re using the built-in sum() and list comprehension which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(1), as we’re not using additional space
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 bisect
test_list = [ 6 , 3 , 7 , 1 , 2 , 4 ]
print ( "The original list is : " + str (test_list))
temp = sorted (test_list)
res = [ len (test_list) - bisect.bisect_left(temp, ele) for ele in test_list]
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 3:Using a for loop and if statement
Python3
test_list = [ 6 , 3 , 7 , 1 , 2 , 4 ]
print ( "The original list is : " + str (test_list))
res = []
for sub in test_list:
count = 0
for ele in test_list:
if sub < = ele:
count + = 1
res.append(count)
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]
Time complexity: O(n)
Auxiliary Space: O(n)
Method 4: Approach using a dictionary
Python3
test_list = [ 6 , 3 , 7 , 1 , 2 , 4 ]
print ( "The original list is : " + str (test_list))
counts = {}
for i in test_list:
counts[i] = len ([j for j in test_list if j > = i])
result = [counts[i] for i in test_list]
print ( "Greater elements Frequency list : " + str (result))
|
Output
The original list is : [6, 3, 7, 1, 2, 4]
Greater elements Frequency list : [2, 4, 1, 6, 5, 3]
Step-by-step algorithm:
- Initialize the list of numbers test_list with the given input.
- Initialize an empty dictionary counts to store the count of elements greater than or equal to each element.
- Loop through each element in the list using a for loop.
- Inside the loop, calculate the count of elements greater than or equal to the current element by using a list comprehension. The list comprehension creates a new list of all elements in test_list that are greater than or equal to the current element i, and the len() function is used to count the number of elements in the list.
- Add an entry to the counts dictionary for the current element i, with the count calculated in step 4 as the value.
- Construct the final result list by using a list comprehension to extract the count for each element in test_list from the counts dictionary.
- Print the final result list.
Time complexity:
The time complexity of the algorithm is O(n^2), where n is the length of the input list test_list. This is because the algorithm loops through each element in the list, and for each element, it loops through the entire list again to count the number of elements greater than or equal to the current element. Therefore, the total number of operations performed is proportional to n*n.
Auxiliary space complexity:
The auxiliary space complexity of the algorithm is O(n), where n is the length of the input list test_list. This is because the counts dictionary stores an entry for each element in the input list, and the size of the dictionary is proportional to n. The final result list also has n elements, so the space complexity of the algorithm is linear with respect to the length of the input list.
Method 5: Using recursion:
Algorithm:
1.We define a recursive function count_greater_or_equal_elements that takes in the list test_list, dictionaries counts, result, and integer i as parameters.
2.The function first checks if i is equal to the length of test_list. If it is, the function returns result.
3.Otherwise, the function calculates the count of elements greater than or equal to the current element current_element at index i in test_list.
4.The function stores this count in the counts dictionary with the current_element as key and count as value.
5.The function appends the count to the result list.
6.The function then recursively calls itself with the updated counts, result, and i values.
Python3
def count_greater_or_equal_elements(test_list, counts = {}, result = [], i = 0 ):
if i = = len (test_list):
return result
current_element = test_list[i]
count = len ([j for j in test_list if j > = current_element])
counts[current_element] = count
result.append(count)
return count_greater_or_equal_elements(test_list, counts, result, i + 1 )
test_list = [ 6 , 3 , 7 , 1 , 2 , 4 ]
print ( "The original list is : " + str (test_list))
result = count_greater_or_equal_elements(test_list)
print ( "Greater elements Frequency list : " + str (result))
|
Output
The original list is : [6, 3, 7, 1, 2, 4]
Greater elements Frequency list : [2, 4, 1, 6, 5, 3]
Time complexity:
The time complexity of the algorithm is O(n^2), where n is the length of the input list.
This is because for each element in the list, we need to compare it to every other element in the list to determine the count of elements greater than or equal to it. This results in a nested loop structure, giving a time complexity of O(n^2).
Auxiliary Space:
The space complexity of the algorithm is O(n), where n is the length of the input list.
This is because we need to create a dictionary counts with n key-value pairs to store the count of elements greater than or equal to each element in the list. We also need to create a list result of size n to store the result. Additionally, we use recursion which results in n function call stack frames. Therefore, the total space complexity is O(n).
Method 6: Using numpy
Step-by-step approach:
- Initialize an empty list “result” to store the frequency of greater elements for each element in the input list.
- Convert the input list “test_list” into a NumPy array.
- Loop through each element “x” in the input list “test_list“.
- Create a boolean NumPy array by comparing each element in the NumPy array with “x“.
- Calculate the sum of the boolean array using the NumPy “np.sum()” function to count the number of elements greater than or equal to “x“.
- Append the result to the “result” list.
- Return the “result” list.
Python3
import numpy as np
test_list = [ 6 , 3 , 7 , 1 , 2 , 4 ]
print ( "The original list is : " + str (test_list))
result = [np. sum (np.array(test_list) > = x) for x in test_list]
print ( "Greater elements Frequency list : " + str (result))
|
Output
The original list is : [6, 3, 7, 1, 2, 4]
Greater elements Frequency list : [2, 4, 1, 6, 5, 3]
Time complexity: O(n^2) due to the nested loops in calculating the frequency for each element in the input list.
Auxiliary space: O(n) to store the “result” list.
Similar Reads
Python | Find sum of frequency of given elements in the list
Given two lists containing integers, the task is to find the sum of the frequency of elements of the first list in the second list. Example: Input: list1 = [1, 2, 3] list2 = [2, 1, 2, 1, 3, 5, 2, 3] Output: 7 Explanation: No of time 1 occurring in list2 is :2 No of time 2 occurring in list2 is :3 No
4 min read
Python | Find most frequent element in a list
Given a list, find the most frequent element in it. If multiple elements appear a maximum number of times, print any one of them using Python. Example Make a set of the list so that the duplicate elements are deleted. Then find the highest count of occurrences of each element in the set and thus, we
2 min read
How to Get the Number of Elements in a Python List?
In Python, lists are one of the most commonly used data structures to store an ordered collection of items. In this article, we'll learn how to find the number of elements in a given list with different methods. Example Input: [1, 2, 3.5, geeks, for, geeks, -11]Output: 7 Let's explore various ways t
3 min read
Python | Find top K frequent elements from a list of tuples
Given a list of tuples with word as first element and its frequency as second element, the task is to find top k frequent element. Below are some ways to above achieve the above task. Method #1: Using defaultdict C/C++ Code # Python code to find top 'k' frequent element # Importing import collection
5 min read
Python program to print Rows where all its Elements' frequency is greater than K
Given Matrix, extract all rows whose all elements have a frequency greater than K. Input : test_list = [[1, 1, 2, 3, 2, 3], [4, 4, 5, 6, 6], [1, 1, 1, 1], [4, 5, 6, 8]], K = 2 Output : [[1, 1, 1, 1]] Explanation : Here, frequency of 1 is 4 > 2, hence row retained. Input : test_list = [[1, 1, 2, 3
8 min read
Python - Step Frequency of elements in List
Sometimes, while working with Python, we can have a problem in which we need to compute frequency in list. This is quite common problem and can have usecase in many domains. But we can atimes have problem in which we need incremental count of elements in list. Let's discuss certain ways in which thi
4 min read
Python - Extract elements with Frequency greater than K
Given a List, extract all elements whose frequency is greater than K. Input : test_list = [4, 6, 4, 3, 3, 4, 3, 4, 3, 8], K = 3 Output : [4, 3] Explanation : Both elements occur 4 times. Input : test_list = [4, 6, 4, 3, 3, 4, 3, 4, 6, 6], K = 2 Output : [4, 3, 6] Explanation : Occur 4, 3, and 3 time
7 min read
Python - Fractional Frequency of elements in List
Given a List, get fractional frequency of each element at each position. Input : test_list = [4, 5, 4, 6, 7, 5, 4, 5, 4] Output : ['1/4', '1/3', '2/4', '1/1', '1/1', '2/3', '3/4', '3/3', '4/4'] Explanation : 4 occurs 1/4th of total occurrences till 1st index, and so on.Input : test_list = [4, 5, 4,
5 min read
Find Number of M Contiguous Elements of a List with a Given Sum - Python
The task is to find how many subsets of length m exist in a list such that their sum is equal to a given value. For example, if the input list is [1, 2, 3, 4, 5], m = 2 and the target sum is 5, the subsets [2, 3] and [1, 4] satisfy the condition. Let's go through multiple methods to solve this probl
3 min read
Python program to find the frequency of the elements which are common in a list of strings
Given list of strings. The task is to find the frequency of the elements which are common in all strings given in the list of strings. Examples: Input : test_list = ["gegek", "gfgk", "kingg"] Output : {'g': 2, 'k': 1} Explanation : g occurs twice in all Strings. Input : test_list = ["gefgek", "gfgk"
3 min read