Python - Sort Matrix by K Sized Subarray Maximum Sum
Last Updated :
01 May, 2023
Given Matrix, write a Python program to sort rows by maximum of K sized subarray sum.
Examples:
Input : test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]], K = 3
Output : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]]
Explanation : 12 = 12 = 12 < 21, is order of maximum sum 3 length substring.
Input : test_list = [[4, 3, 5, 2, 3], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]], K = 3
Output : [[4, 3, 5, 2, 3], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]]
Explanation : 12 = 12 < 21, is order of maximum sum 3 length substring.
Method #1 : Using max() + sum() + slicing + sort()
In this, maximum of K length subarray is computed using max(), sum() and slicing using external function and inplace sorting is done using sort().
Python3
# Python3 code to demonstrate working of
# Sort Matrix by K Sized Subarray Maximum Sum
# Using max() + sum() + slicing + sort()
def max_ksub(row):
# getting maximum K length sum
return max(sum(row[idx: idx + K]) for idx in range(len(row) - K))
# initializing list
test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1],
[4, 3, 9, 3, 9], [5, 4, 3, 2, 1]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# performing inplace sorting
test_list.sort(key=max_ksub)
# printing result
print("The sorted result : " + str(test_list))
Output:
The original list is : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]] The sorted result : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]]
Time Complexity: O(nlogn+mlogm)
Auxiliary Space: O(1)
Method #2 : Using sorted() + lambda + max() + sum() + slicing
In this, we perform task of sorting using sorted() + lambda function which injects comparator logic and avoids calling external function.
Python3
# Python3 code to demonstrate working of
# Sort Matrix by K Sized Subarray Maximum Sum
# Using sorted() + lambda + max() + sum() + slicing
# initializing list
test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1],
[4, 3, 9, 3, 9], [5, 4, 3, 2, 1]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# sorted() performs inplace sort
# lambda function injects comparison logic
res = sorted(test_list, key=lambda row: max(
sum(row[idx: idx + K]) for idx in range(len(row) - K)))
# printing result
print("The sorted result : " + str(res))
Output:
The original list is : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]] The sorted result : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]]
Time Complexity: O(nlogn+mlogm)
Auxiliary Space: O(n)
Method 3: Using heapq.nlargest() + sum() + enumerate()
Python3
# Python3 code to demonstrate working of
# Sort Matrix by K Sized Subarray Maximum Sum
# Using heapq.nlargest() + sum() + enumerate()
# importing required module
import heapq
# initializing list
test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1],
[4, 3, 9, 3, 9], [5, 4, 3, 2, 1]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# heapq.nlargest() returns the n largest elements from the iterable
# lambda function calculates the sum of K-sized subarrays of a row
# enumerate() adds index to the result of heapq.nlargest()
# sorted() sorts the rows based on their K-sized subarray maximum sum
res = sorted(test_list, key=lambda row: heapq.nlargest(1, ((sum(row[i:i+K]), i) for i in range(len(row) - K + 1)), key=lambda x: x[0])[0][1])
# printing result
print("The sorted result : " + str(res))
OutputThe original list is : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]]
The sorted result : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]]
Time complexity: O(n * k * log(n)), where n is the number of rows and k is the subarray size.
Auxiliary space: O(n * k).
Similar Reads
Python - Sort Matrix by Maximum String Length
Given a matrix, perform row sort basis on the maximum length of the string in it. Input : test_list = [['gfg', 'best'], ['geeksforgeeks'], ['cs', 'rocks'], ['gfg', 'cs']] Output : [['gfg', 'cs'], ['gfg', 'best'], ['cs', 'rocks'], ['geeksforgeeks']] Explanation : 3 < 4 < 5 < 13, maximum leng
3 min read
Python3 Program for Size of The Subarray With Maximum Sum
An array is given, find length of the subarray having maximum sum.Examples : Input : a[] = {1, -2, 1, 1, -2, 1}Output : Length of the subarray is 2Explanation: Subarray with consecutive elements and maximum sum will be {1, 1}. So length is 2Input : ar[] = { -2, -3, 4, -1, -2, 1, 5, -3 }Output : Leng
4 min read
Python program to Sort Matrix by Maximum Row element
Given a Matrix, sort rows by maximum element. Input : test_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]] Explanation : 18, 10, 8 and 5 are maximum elements in rows, hence sorted. Input : test_list = [[9, 10, 3], [10, 18, 3], [0, 3, 5]
4 min read
Python Program to Sort Matrix by Sliced Row and Column Summation
Given a Matrix and a range of indices, the task is to write a python program that can sort a matrix on the basis of the sum of only given range of indices of each row and column i.e. the rows and columns are to sliced from a given start to end index, further, matrix are sorted using only those slice
8 min read
Python | Maximum Sum Sublist
The task is to find a contiguous sublist (i.e., a sequence of elements that appear consecutively in the original list) such that the sum of the elements in this sublist is as large as possible. We need to return the maximum sum of this sublist. Let's explore methods to find Maximum Sum Sublist in py
2 min read
Python - Sort Matrix by Row Median
Given a Matrix, sort by median of each row. Input : test_list = [[3, 4, 7], [1, 7, 2], [10, 2, 4], [8, 6, 5]] Output : [[1, 7, 2], [3, 4, 7], [10, 2, 4], [8, 6, 5]] Explanation : 2 < 3 < 4 < 6, sorted increasingly by median element. Input : test_list = [[3, 4, 7], [1, 7, 2], [8, 6, 5]] Outp
4 min read
Python - Row with Minimum Sum in Matrix
We can have an application for finding the lists with the minimum value and print it. This seems quite an easy task and may also be easy to code, but having shorthands to perform the same are always helpful as this kind of problem can come in web development. Method #1 : Using reduce() + lambda The
4 min read
Python program to sort matrix based upon sum of rows
Given a Matrix, perform sort based upon the sum of rows. Input : test_list = [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]] Output : [[2, 1], [4, 5], [4, 6, 1], [2, 5, 7]] Explanation : 3 < 9 < 11 < 14. Sorted sum. Input : test_list = [[4, 5], [2, 5, 7], [4, 6, 1]] Output : [[4, 5], [4, 6, 1], [2,
6 min read
Python - Sort list of lists by the size of sublists
The problem is to sort a list of lists based on the size of each sublist. For example, given the list [[1, 2], [1], [1, 2, 3]], the sorted result should be [[1], [1, 2], [1, 2, 3]] when sorted in ascending order. We will explore multiple methods to do this in Python.Using sorted() with len() This me
3 min read
Python program to Sort Tuples by their Maximum element
Given a Tuple List sort tuples by maximum element in a tuple. Input : test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)] Output : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)] Explanation : 19 > 7 = 7 > 2, is order, hence reverse sorted by maximum element. Input : test_list
5 min read