- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Sort Matrix by K Sized Subarray Maximum Sum
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.
- Related Articles
- C++ program to find maximum of each k sized contiguous subarray
- Python – Sort Matrix by Maximum String Length
- Python - Sort Matrix by Maximum Row element
- Maximum Size Subarray Sum Equals k in C++
- Maximum subarray sum by flipping signs of at most K array elements in C++
- Maximum subarray sum in array formed by repeating the given array k times in C++
- Program to find maximum ascending subarray sum using Python
- Program to find the maximum sum of the subarray modulo by m in Python
- Find maximum (or minimum) sum of a subarray of size k in C++
- Subarray Sum Equals K in C++
- Python – Sort Matrix by total characters
- Python – Sort Matrix by Row Median
- Python – Sort Matrix by None frequency
- Python – Sort Matrix by Palindrome count
- Python – Sort row by K multiples

Advertisements