Open In App

Python – Find the frequency of numbers greater than each element in a list

Last Updated : 20 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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]

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))


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




# 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.


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




# 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))


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:

  1. Initialize the list of numbers test_list with the given input.
  2. Initialize an empty dictionary counts to store the count of elements greater than or equal to each element.
  3. Loop through each element in the list using a for loop.
  4. 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.
  5. Add an entry to the counts dictionary for the current element i, with the count calculated in step 4 as the value.
  6. Construct the final result list by using a list comprehension to extract the count for each element in test_list from the counts dictionary.
  7. 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.


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 all pairs of consecutive odd positive integer smaller than a with sum greater than b
Given two positive integers a and b, the task is to write a program in python to find all pairs of consecutive odd numbers which are smaller than the first number a and their sum should be greater than the second number b. Examples: Input: a = 60 b = 100 Output: Pairs of consecutive number are: 51 , 53 53 , 55 55 , 57 57 , 59 Input: a = 20 b = 200
3 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 times respectively. Method #1 : Using count() + loop I
7 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 &gt; 2, hence row retained. Input : test_list = [[1, 1, 2, 3, 2, 3], [4, 4, 5, 6, 6], [1, 3, 4, 1], [4, 5, 6,
8 min read
Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
Given a string S, the task is to find the prefix of string S with the maximum possible length such that frequency of each character in the prefix is at most the number of characters in S with minimum frequency. Examples: Input: S = 'aabcdaab' Output: aabcd Explanation: Frequency of characters in the given string - {a: 4, b: 2, c: 1, d: 1} Minimum f
8 min read
Python - Test if greater than preceding element in Tuple List
Given list of tuples, check if preceding element is smaller than the current element for each element in Tuple list. Input : test_list = [(5, 1), (4, 9), (3, 5)] Output : [[False, False], [False, True], [False, True]] Explanation : First element always being False, Next element is checked for greater value. Input : test_list = [(1, 8), (2, 2), (3,
9 min read
Python | Find smallest element greater than K
Given a list, write a Python program to find the smallest number which is greater than a specific element K. Let's see all the approaches to solve this problem, from naive to one-liners so that they can be used in programming whenever required. Method #1: Naive Method Using loop we keep on re-initializing the named variable if we find the element s
6 min read
Sum of all array elements less than X and greater than Y for Q queries
Given a sorted array arr[], and a set Q having M queries, where each query has values X and Y, the task is to find the sum of all integers less than X and greater than Y present in the array. Note: X and Y may or may not be present in the array. Examples: Input: arr[] = [3 5 8 12 15], Q = {{5, 12}, {4, 8}} Output: 18 30 Explanation: For query 1, X
9 min read
Python | Get the Index of first element greater than K
Python list operations are always desired to have shorthands as they are used in many places in development. Hence having knowledge of them always remains quite useful. Let's deals with finding one such utility of having index of first element greater than K by one-liner. There are various ways in which this can be achieved. Method #1 : Using next(
6 min read
Python - Sort Matrix by Number of elements greater than its previous element
Given a Matrix, sort by occurrences where next element is greater than current. Compute the count of i &lt; i + 1 in each list, sort each row by count of each of this condition in each row. Input : test_list = [[4, 6, 2, 9, 10], [5, 3, 2, 5], [2, 4, 5, 6, 7, 7], [6, 3, 2]] Output : [[6, 3, 2], [5, 3, 2, 5], [4, 6, 2, 9, 10], [2, 4, 5, 6, 7, 7]] Exp
4 min read
Python - Extract element with relative difference greater than K
Given a list of numbers, the task is to write a Python program to extract all numbers with differences of the next and previous elements with a current greater than K. Input : test_list = [2, 7, 4, 1, 9, 2, 3, 10, 1, 5], K = 4Output : [9, 10]Explanation : 9 has 1 as preceding element and 2 as succeeding. 8 and 7 are its difference respectively whic
4 min read
Practice Tags :