Python – Sort Matrix by K Sized Subarray Maximum Sum

PythonServer Side ProgrammingProgramming

When it is required to sort matrix by k sized subarray maximum sum, a method is defined that uses the ‘amx’ and ‘sum’ methods and iterates over the list.

Example

Below is a demonstration of the same

def sort_marix_K(my_list):
   return max(sum(my_list[index: index + K]) for index in range(len(my_list) - K))

my_list = [[51, 23, 4, 24, 1], [45, 6, 26, 36, 5], [56, 16, 6, 36, 8], [5, 4, 36, 26, 26]]

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

K = 4
print("The value of K is ")
print(K)
my_list.sort(key=sort_marix_K)

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

Output

The list is :
[[51, 23, 4, 24, 1], [45, 6, 26, 36, 5], [56, 16, 6, 36, 8], [5, 4, 36, 26, 26]]
The value of K is
4
The resultant list is :
[[5, 4, 36, 26, 26], [51, 23, 4, 24, 1], [45, 6, 26, 36, 5], [56, 16, 6, 36, 8]]

Explanation

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

  • It iterates through the list and determines the index and gets the sum of specific indices, and gets the maximum of these values.

  • This is returned as output.

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

  • The value of K is defined and displayed on the console.

  • The list is sorted based on the previously defined method.

  • The output is displayed on the console.

raja
Published on 20-Sep-2021 08:21:52
Advertisements