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
# 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))
OutputThe 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 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))
OutputThe 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
# initializing list
test_list = [6, 3, 7, 1, 2, 4]
# printing original list
print("The original list is : " + str(test_list))
# using for loop and if statement
res = []
for sub in test_list:
count = 0
for ele in test_list:
if sub <= ele:
count += 1
res.append(count)
# printing result
print("Greater elements Frequency list : " + str(res))
#This code is contributed by Vinay Pinjala.
OutputThe 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
# Initialize the list of numbers
test_list = [6, 3, 7, 1, 2, 4]
# Print the original list
print("The original list is : " + str(test_list))
# Initialize an empty dictionary to store the count of elements greater than or equal to each element
counts = {}
# Loop through each element in the list
for i in test_list:
# Calculate the count of elements greater than or equal to the current element
counts[i] = len([j for j in test_list if j >= i])
# Construct the final result list using the values in the counts dictionary
result = [counts[i] for i in test_list]
# Print the final result list
print("Greater elements Frequency list : " + str(result))
OutputThe 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):
# Base case: If all elements in the list have been processed, return the final result
if i == len(test_list):
return result
# Recursive case: Calculate the count of elements greater than or equal to the current element
current_element = test_list[i]
count = len([j for j in test_list if j >= current_element])
counts[current_element] = count
# Add the count to the result list
result.append(count)
# Recursively process the rest of the list
return count_greater_or_equal_elements(test_list, counts, result, i+1)
# Initialize the list of numbers
test_list = [6, 3, 7, 1, 2, 4]
# Print the original list
print("The original list is : " + str(test_list))
# Call the recursive function to calculate the count of elements greater than or equal to each element
result = count_greater_or_equal_elements(test_list)
# Print the final result list
print("Greater elements Frequency list : " + str(result))
#This code is contributed by Jyothi pinjala.
OutputThe 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 Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read