Python – Sort Matrix by Number of elements greater than its previous element

PythonServer Side ProgrammingProgramming

When it is required to sort a matrix based on the number of elements that is greater than the previous element, a list comprehension and the ‘len’ method is used by using a function.

Below is a demonstration of the same −

Example

 Live Demo

def fetch_greater_freq(row):

   return len([row[idx] for idx in range(0, len(row) - 1) if row[idx] < row[idx + 1]])

my_list = [[11, 3, 25, 99, 10], [5, 3, 25, 4], [77, 11, 5, 3, 77, 77], [11, 3, 25]]

print("The list is :")
print(my_list)

my_list.sort(key=fetch_greater_freq)

print("The resultant list is :")
print(my_list)

Output

The list is :
[[11, 3, 25, 99, 10], [5, 3, 25, 4], [77, 11, 5, 3, 77, 77], [11, 3, 25]]
The resultant list is :
[[5, 3, 25, 4], [77, 11, 5, 3, 77, 77], [11, 3, 25], [11, 3, 25, 99, 10]]

Explanation

  • A method named ‘fetch_greater_freq’ is defined that takes a list as a parameter.

  • The list is iterated over, and a specific element is accessed and checked to see if it is less than its consecutive element.

  • Its length is returned as output of the method.

  • Outside the method, a list of list of integers is defined and is displayed on the console.

  • The list is sorted using the sort method by passing the previously defined method as the parameter.

  • The output is displayed on the console.

raja
Published on 04-Sep-2021 10:54:50
Advertisements