Python Program to print a specific number of rows with Maximum Sum
Last Updated :
12 May, 2023
Given a Matrix, the following article extracts a specifies number of rows that has a maximum sum.
Input : test_list = [[3, 4, 5, 6], [1, 4, 6], [199], [2, 3, 4, 5, 6], [7, 3, 1]], K = 3
Output : [[199], [2, 3, 4, 5, 6], [3, 4, 5, 6]]
Explanation : 199 > 20 > 18, 3 maximum elements rows are extracted.
Input : test_list = [[3, 4, 5, 6], [1, 4, 6], [199], [2, 3, 4, 5, 6], [7, 3, 1]], K = 2
Output : [[199], [2, 3, 4, 5, 6]]
Explanation : 199 > 20, 2 maximum elements rows are extracted.
Method 1 : Using sorted(), reverse, slice and sum()
In this, we perform the task of sorting using sorted() and getting sum using sum(). Reverse key is used to perform reversal of rows for getting maximum summation rows at top and then top K(specific number of rows) rows are sliced.
Python3
test_list = [[ 3 , 4 , 5 , 6 ], [ 1 , 4 , 6 ], [ 199 ], [ 2 , 3 , 4 , 5 , 6 ], [ 7 , 3 , 1 ]]
print ( "The original list is : " + str (test_list))
K = 3
res = sorted (test_list, key = lambda row: sum (row), reverse = True )[:K]
print ( "The filtered rows : " + str (res))
|
Output:
The original list is : [[3, 4, 5, 6], [1, 4, 6], [199], [2, 3, 4, 5, 6], [7, 3, 1]]
The filtered rows : [[199], [2, 3, 4, 5, 6], [3, 4, 5, 6]]
Time Complexity: O(nlogn+mlogm)
Auxiliary Space: O(k)
Method 2 : Using sort(), reverse, slicing and sum()
In this, we perform the task of in-place sorting using sort(), using reverse as key. Slicing is done using slice operation. The sum(), is used to take summation, and an external function is called to compute sum of rows of the list.
Python3
def row_sum(row):
return sum (row)
test_list = [[ 3 , 4 , 5 , 6 ], [ 1 , 4 , 6 ], [ 199 ], [ 2 , 3 , 4 , 5 , 6 ], [ 7 , 3 , 1 ]]
print ( "The original list is : " + str (test_list))
K = 3
test_list.sort(key = row_sum, reverse = True )
res = test_list[:K]
print ( "The filtered rows : " + str (res))
|
Output:
The original list is : [[3, 4, 5, 6], [1, 4, 6], [199], [2, 3, 4, 5, 6], [7, 3, 1]]
The filtered rows : [[199], [2, 3, 4, 5, 6], [3, 4, 5, 6]]
Time Complexity: O(nlogn+mlogm)
Auxiliary Space: O(k)
Method 3: Using the heapq module and maintaining a heap of size K.
Approach:
- Import the heapq module.
- Define the function row_sum() to return the sum of a row.
- Initialize a heap of size K with an initial value of None.
- Iterate through each row in the test_list.
- Calculate the row sum for the current row using the row_sum() function.
- If the heap is not full or if the current row sum is greater than the smallest element in the heap, push the current row and its sum onto the heap.
- If the heap is full and the current row sum is less than or equal to the smallest element in the heap, continue to the next row.
- Once all rows have been processed, pop the K largest elements from the heap.
- Reverse the resulting list and return it as the filtered rows.
Python3
import heapq
def row_sum(row):
return sum (row)
test_list = [[ 3 , 4 , 5 , 6 ], [ 1 , 4 , 6 ], [ 199 ], [ 2 , 3 , 4 , 5 , 6 ], [ 7 , 3 , 1 ]]
K = 3
heap = [() for i in range (K)]
for row in test_list:
row_sum_val = row_sum(row)
if not all (heap) or row_sum_val > heap[ 0 ][ 0 ]:
heapq.heappushpop(heap, (row_sum_val, row))
res = [row for sum_val, row in heapq.nlargest(K, heap)]
res.reverse()
print ( "The filtered rows: " + str (res))
|
Output
The filtered rows: [[3, 4, 5, 6], [2, 3, 4, 5, 6], [199]]
The time complexity for this approach is O(N*log(K)), where N is the total number of elements in the list. The auxiliary space complexity is O(K), which is the size of the heap.
Method 4: Using numpy library
Approach:
- Import the numpy library.
- Convert test_list to a numpy array using the numpy.array() function.
- Use the numpy.sum() function to calculate the sum of each row of the array.
- Use the numpy.argsort() function to get the indices of the rows sorted in descending order of row sums.
- Use slicing to get the first K rows from the sorted indices.
- Use the numpy.take() function to get the rows corresponding to the sorted indices.
- Convert the resulting array back to a list using the numpy.ndarray.tolist() method.
Python3
import numpy as np
def row_sum(row):
return sum (row)
test_list = [[ 3 , 4 , 5 , 6 ], [ 1 , 4 , 6 ], [ 199 ], [ 2 , 3 , 4 , 5 , 6 ], [ 7 , 3 , 1 ]]
K = 3
max_row_length = max ( len (row) for row in test_list)
for i in range ( len (test_list)):
row = test_list[i]
row + = [ 0 ] * (max_row_length - len (row))
arr = np.array(test_list)
row_sums = np. sum (arr, axis = 1 )
sorted_indices = np.argsort(row_sums)[:: - 1 ]
k_sorted_indices = sorted_indices[:K]
result_arr = np.take(arr, k_sorted_indices, axis = 0 )
result_list = [row[:max_row_length] for row in result_arr.tolist()]
print ( "The filtered rows : " + str (result_list))
|
OUTPUT:
The filtered rows: [[3, 4, 5, 6], [2, 3, 4, 5, 6], [199]]
Time complexity: O(NlogN + KlogK), where N is the total number of elements in test_list.
Auxiliary space: O(N)
Similar Reads
Python Program for Number of pairs with maximum sum
Write a python program for a given array arr[], count number of pairs arr[i], arr[j] such that arr[i] + arr[j] is maximum and i < j. Example: Input : arr[] = {1, 1, 1, 2, 2, 2}Output: 3Explanation: The maximum possible pair sum where i<j is 4, which is given by 3 pairs, so the answer is 3 the
3 min read
Python Program Maximum of Three Number using Lambda
Here we will create a lambda function to find the maximum among three numbers in Python. Example: Input: a=10, b=24, c=15Output: 24 # using LambdaFinding Maximum Among Three Numbers in PythonBelow are some of the ways by which we can find the maximum among three numbers in Python. Using lambda with
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 : Len
4 min read
Python - Maximum Pair Summation in numeric String
Sometimes, we might have a problem in which we require to get the maximum summation of 2 numbers from Strings but with a constraint of having the numbers in successions. This type of problem can occur while competitive programming. Letâs discuss certain ways in which this problem can be solved. Meth
6 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
Python3 Program to Find Maximum value possible by rotating digits of a given number
Given a positive integer N, the task is to find the maximum value among all the rotations of the digits of the integer N. Examples: Input: N = 657Output: 765Explanation: All rotations of 657 are {657, 576, 765}. The maximum value among all these rotations is 765. Input: N = 7092Output: 9270Explanati
2 min read
Python program to print Aitken's array
Given a number n. The task is to print the Aikten's array upto n. Examples: Input: 5 Output: [1] [1, 2] [2, 3, 5] [5, 7, 10, 15] [15, 20, 27, 37, 52] Input: 7 Output: [1] [1, 2] [2, 3, 5] [5, 7, 10, 15] [15, 20, 27, 37, 52] [52, 67, 87, 114, 151, 203] [203, 255, 322, 409, 523, 674, 877] To print it
2 min read
Python Program for Maximum size square sub-matrix with all 1s
Write a Python program for a given binary matrix, the task is to find out the maximum size square sub-matrix with all 1s. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.Approach: Let the given binary matrix be M[R][C]. The idea of the algorithm is to construct an
4 min read
Python program maximum of three
The task of finding the maximum of three numbers in Python involves comparing three input values and determining the largest among them using various techniques. For example, if a = 10, b = 14, and c = 12, the result will be 14. Using max()max() is the straightforward approach to find the maximum of
3 min read
Python program to find Cumulative sum of a list
Calculating the cumulative sum of a list means finding the running total of the elements as we move through the list. In this article, we will explore How to find the cumulative sum of a list. Using itertools.accumulate()This is the most efficient method for calculating cumulative sums. itertools mo
3 min read