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
Selected Reading
Python Program to Sort Matrix Rows by summation of consecutive difference of elements
This article demonstrates how to sort matrix rows by the summation of consecutive differences between adjacent elements. We calculate the absolute difference between consecutive elements in each row, sum them up, and use this sum as the sorting key.
Understanding Consecutive Differences
For a row like [97, 6, 47, 3], the consecutive differences are ?
- |6 - 97| = 91
- |47 - 6| = 41
- |3 - 47| = 44
- Sum = 91 + 41 + 44 = 176
Example
Here's a complete program that sorts matrix rows by their consecutive difference summation ?
def diff_summation_elem(row):
return sum([abs(row[index + 1] - row[index]) for index in range(0, len(row) - 1)])
matrix = [[97, 6, 47, 3], [6, 88, 3, 26], [71, 53, 34, 65], [15, 36, 5, 62]]
print("Original matrix:")
print(matrix)
# Calculate sum for each row for demonstration
print("\nConsecutive difference sums:")
for i, row in enumerate(matrix):
diff_sum = diff_summation_elem(row)
print(f"Row {i}: {row} ? Sum: {diff_sum}")
matrix.sort(key=diff_summation_elem)
print("\nSorted matrix:")
print(matrix)
Original matrix: [[97, 6, 47, 3], [6, 88, 3, 26], [71, 53, 34, 65], [15, 36, 5, 62]] Consecutive difference sums: Row 0: [97, 6, 47, 3] ? Sum: 176 Row 1: [6, 88, 3, 26] ? Sum: 190 Row 2: [71, 53, 34, 65] ? Sum: 68 Row 3: [15, 36, 5, 62] ? Sum: 109 Sorted matrix: [[71, 53, 34, 65], [15, 36, 5, 62], [97, 6, 47, 3], [6, 88, 3, 26]]
How It Works
The diff_summation_elem() function ?
- Uses list comprehension to iterate through consecutive element pairs
- Calculates absolute difference using
abs(row[index + 1] - row[index]) - Sums all differences using
sum() - Returns the total sum as the sorting key
Alternative Implementation
Using a more concise approach with zip() ?
def consecutive_diff_sum(row):
return sum(abs(b - a) for a, b in zip(row, row[1:]))
matrix = [[97, 6, 47, 3], [6, 88, 3, 26], [71, 53, 34, 65], [15, 36, 5, 62]]
print("Original matrix:")
print(matrix)
sorted_matrix = sorted(matrix, key=consecutive_diff_sum)
print("Sorted matrix:")
print(sorted_matrix)
Original matrix: [[97, 6, 47, 3], [6, 88, 3, 26], [71, 53, 34, 65], [15, 36, 5, 62]] Sorted matrix: [[71, 53, 34, 65], [15, 36, 5, 62], [97, 6, 47, 3], [6, 88, 3, 26]]
Conclusion
Sorting matrix rows by consecutive difference summation helps identify rows with similar value transitions. Use sort(key=function) for in-place sorting or sorted() for creating a new sorted list.
Advertisements
