Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Sort Matrix by Number of elements greater than its previous element
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 with a custom function as the sorting key.
Example
Here's how to sort a matrix by counting ascending pairs in each row ?
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)
The output of the above code is ?
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]]
How It Works
Let's break down how the sorting works for each row ?
def fetch_greater_freq(row):
return len([row[idx] for idx in range(0, len(row) - 1) if row[idx] < row[idx + 1]])
rows = [
[11, 3, 25, 99, 10], # 3<25, 25<99 = 2 ascending pairs
[5, 3, 25, 4], # 3<25 = 1 ascending pair
[77, 11, 5, 3, 77, 77], # 3<77 = 1 ascending pair
[11, 3, 25] # 3<25 = 1 ascending pair, but comes later
]
for row in rows:
count = fetch_greater_freq(row)
print(f"{row} has {count} ascending pairs")
[11, 3, 25, 99, 10] has 2 ascending pairs [5, 3, 25, 4] has 1 ascending pairs [77, 11, 5, 3, 77, 77] has 1 ascending pairs [11, 3, 25] has 1 ascending pairs
Alternative Implementation
You can also implement this using a simple loop instead of list comprehension ?
def count_ascending_pairs(row):
count = 0
for i in range(len(row) - 1):
if row[i] < row[i + 1]:
count += 1
return count
matrix = [[11, 3, 25, 99, 10], [5, 3, 25, 4], [77, 11, 5, 3, 77, 77], [11, 3, 25]]
print("Original matrix:")
print(matrix)
matrix.sort(key=count_ascending_pairs)
print("Sorted matrix:")
print(matrix)
Original matrix: [[11, 3, 25, 99, 10], [5, 3, 25, 4], [77, 11, 5, 3, 77, 77], [11, 3, 25]] Sorted matrix: [[5, 3, 25, 4], [77, 11, 5, 3, 77, 77], [11, 3, 25], [11, 3, 25, 99, 10]]
Key Points
The
fetch_greater_freq()function counts pairs whererow[i] < row[i+1]The
sort()method uses this function as a key to determine sorting orderRows with fewer ascending pairs appear first in the sorted result
When counts are equal, Python's stable sort preserves the original order
Conclusion
This approach effectively sorts matrix rows by counting ascending adjacent pairs. The custom key function with sort() provides a clean solution for complex sorting criteria in Python.
