Python Program to print a specific number of rows with Maximum Sum

Python Program to print a specific number of rows with Maximum Sum

Let's construct a tutorial to retrieve and print a specified number of rows with the maximum sum from a 2D list (or matrix).

Objective:

Given a 2D list (or matrix) and a number k, our goal is to find and print the k rows which have the highest sum of elements.

Example:

For the matrix:

[ [5, 2, 3], [1, 4, 6], [7, 8, 9], [10, 5, 1] ] 

And k = 2, the rows with the highest sum are [7, 8, 9] and [10, 5, 1].

Approach:

  1. Calculate the sum for each row in the matrix.
  2. Store each row along with its sum in a list of tuples.
  3. Sort this list based on the sums.
  4. Print the first k rows from the sorted list.

Python Implementation:

def rows_with_max_sum(matrix, k): # Compute the sum for each row and store as (sum, row) tuples sum_rows = [(sum(row), row) for row in matrix] # Sort the list of tuples in descending order based on the sum sum_rows.sort(reverse=True, key=lambda x: x[0]) # Print the first k rows for i in range(k): print(sum_rows[i][1]) # Test matrix = [ [5, 2, 3], [1, 4, 6], [7, 8, 9], [10, 5, 1] ] k = 2 rows_with_max_sum(matrix, k) 

Expected Output:

[10, 5, 1] [7, 8, 9] 

Test & Verify:

Try with different matrices and values of k to ensure the program's accuracy:

matrix2 = [ [1, 2], [3, 4], [5, 6], [7, 8] ] k = 1 rows_with_max_sum(matrix2, k) # Expected output: [7, 8] 

Notes:

  • The provided solution sorts the rows based on their sums. This operation has a time complexity of O(n log n), where n is the number of rows. If k is very small compared to n, a more efficient approach would be to use a priority queue or heap to get the top k rows.
  • This program assumes the matrix has at least k rows. You might want to add checks or handle cases where the matrix has fewer than k rows.
  • For simplicity, the program directly prints the rows. Depending on requirements, you might want to return the rows as a list instead.

More Tags

react-native-navigation-v2 aws-glue handbrake cp1252 naming-conventions datatrigger django-orm indexoutofboundsexception nameerror kivy

More Programming Guides

Other Guides

More Programming Examples