Open In App

Python Program to Sort Matrix Rows by summation of consecutive difference of elements

Last Updated : 18 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Matrix, the following article depicts how to sort rows of a matrix on the basis of summation of difference between consecutive elements of a row.

Input : test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]], 
Output : [[4, 3, 2, 1], [7, 2, 4, 5], [1, 5, 3, 6], [6, 9, 3, 2]] 
Explanation : 4 < 8 < 9 < 10 is consecutive difference summation.
Input : test_list = [[1, 5, 3, 6], [7, 2, 4, 5], [6, 9, 3, 2]], 
Output : [[7, 2, 4, 5], [1, 5, 3, 6], [6, 9, 3, 2]] 
Explanation : 8 < 9 < 10 is consecutive difference summation. 

Method 1 : Using sort() and abs()

In this, we perform the task of in-place sorting using sort(), and abs() is used to get the absolute value of the summation of consecutive differences.

Python3




# get abs summation
def diff_sum(row):
    return sum([abs(row[idx + 1] - row[idx]) for idx in range(0, len(row) - 1)])
 
 
# initializing list
test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# performing inplace sort
test_list.sort(key=diff_sum)
 
# printing result
print("Sorted Rows : " + str(test_list))


Output

The original list is : [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
Sorted Rows : [[4, 3, 2, 1], [7, 2, 4, 5], [1, 5, 3, 6], [6, 9, 3, 2]]

Time Complexity: O(nlogn+mlogm)
Auxiliary Space: O(k)

Method 2 : Using sorted(), lambda, abs() and sum()

In this, the sorting is done using sorted() and lambda function is used to inject conditional statement in sorted(). 

Steps by step approach : 

  1. Initialize a list of lists called test_list with four sublists each containing four integers.
  2. Print the original list using the print() function.
  3. Sort the sublists in test_list based on the absolute difference between consecutive elements in each sublist. This is achieved using the sorted() function and a lambda function that calculates the sum of the absolute differences between consecutive elements in a sublist.
  4. Assign the sorted list to a new variable called res.
  5. Print the sorted list using the print() function.

Below is the implementation of the above approach:

Python3




# initializing list
test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# performing sort
res = sorted(test_list, key=lambda row: sum(
    [abs(row[idx + 1] - row[idx]) for idx in range(0, len(row) - 1)]))
 
# printing result
print("Sorted Rows : " + str(res))


Output:

The original list is : [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]

Sorted Rows : [[4, 3, 2, 1], [7, 2, 4, 5], [1, 5, 3, 6], [6, 9, 3, 2]]

Time Complexity: O(nlogn+mlogm)
Auxiliary Space: O(k)

Method 3: Using a nested loop to compute the absolute difference between each pair of adjacent elements in each row, then calculate the row-wise sum of these differences and use them to sort the original list. 

Step-by-step approach:

  • Initialize a dictionary to store the row-wise sums of absolute differences.
  • Loop through each row in the original list:
    a. Initialize a variable to store the sum of absolute differences for the current row.
    b. Loop through each adjacent pair of elements in the row, calculate their absolute difference, and add it to the sum.
    c. Add the sum to the dictionary using the current row as the key.
  • Use the dictionary to sort the original list by the row-wise sums of absolute differences.
  • Print the sorted list.

Below is the implementation of the above approach:

Python3




# initializing list
test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# computing row-wise sums of absolute differences
sums_dict = {}
for row in test_list:
    row_sum = 0
    for i in range(len(row)-1):
        row_sum += abs(row[i+1] - row[i])
    sums_dict[tuple(row)] = row_sum
 
# sorting the original list based on row-wise sums of absolute differences
res = [list(row) for row in sorted(test_list, key=lambda x: sums_dict[tuple(x)])]
 
# printing result
print("Sorted Rows : " + str(res))


Output

The original list is : [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
Sorted Rows : [[4, 3, 2, 1], [7, 2, 4, 5], [1, 5, 3, 6], [6, 9, 3, 2]]

Time complexity: O(n^2) where n is the length of the longest row in the list. 
Auxiliary space: O(n) where n is the total number of elements in the list. 

Method 4: Using numpy library and np.argsort() function

Step-by-step approach:

  1. Import the numpy library
  2. Convert the given list of lists into a numpy array using np.array()
  3. Compute the row-wise absolute difference between each pair of adjacent elements using np.abs() and np.diff() functions.
  4. Compute the sum of the absolute differences for each row using np.sum() function.
  5. Sort the rows based on the sum of absolute differences using np.argsort() function.
  6. Finally, use the sorted indices to sort the original array.

Below is the implementation of the above approach:

Python3




import numpy as np
 
# initializing list
test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
 
# convert list to numpy array
arr = np.array(test_list)
 
# compute row-wise absolute difference
diff_arr = np.abs(np.diff(arr, axis=1))
 
# compute sum of absolute differences for each row
sum_arr = np.sum(diff_arr, axis=1)
 
# sort the rows based on sum of absolute differences
sorted_indices = np.argsort(sum_arr)
 
# use sorted indices to sort the original array
sorted_arr = arr[sorted_indices]
 
# print sorted array
print("Sorted Rows: ", sorted_arr.tolist())


Output:

Sorted Rows:  [[4, 3, 2, 1], [7, 2, 4, 5], [1, 5, 3, 6], [6, 9, 3, 2]]

Time complexity: O(nlogn), where n is the number of elements in the input list.
Auxiliary space: O(n), where n is the number of elements in the input list. This is because we are creating a numpy array to store the input list and intermediate arrays to store the absolute differences and sum of absolute differences for each row.

Method 5 : Using a Heap Queue (Priority Queue)

Step-by-step approach:

  1. Import the heapq module to use the heap queue (priority queue) data structure.
  2. Define a custom function diff_sum() that takes a row as input and returns the absolute summation of differences.
  3. Define a new list result to store the sorted rows.
  4. Define an empty heap pq and push each row with its absolute summation of differences as a tuple to the heap. Use the heappush() function from heapq module to push each tuple to the heap.
  5. While the heap is not empty, pop the row with the smallest absolute summation of differences from the heap using the heappop() function from heapq module and append it to the result list.
  6. Return the result list as the sorted list of rows.

Below is the implementation of the above approach:

Python3




import heapq
 
# custom function to calculate absolute summation of differences
def diff_sum(row):
    return sum([abs(row[idx + 1] - row[idx]) for idx in range(0, len(row) - 1)])
 
# list of rows
test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
 
# initialize result list
result = []
 
# push each row with its absolute summation of differences to the heap
pq = []
for row in test_list:
    heapq.heappush(pq, (diff_sum(row), row))
 
# pop the row with smallest absolute summation of differences from the heap and append to result list
while pq:
    result.append(heapq.heappop(pq)[1])
 
# print the sorted list of rows
print("Sorted Rows: ", result)


Output

Sorted Rows:  [[4, 3, 2, 1], [7, 2, 4, 5], [1, 5, 3, 6], [6, 9, 3, 2]]

Time complexity: O(n log n), where n is the total number of elements in the input list of rows
Auxiliary space: O(n), where n is the total number of elements in the input list of rows. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads