Python - Row with Minimum Sum in Matrix

Python - Row with Minimum Sum in Matrix

In this tutorial, we'll explore how to find the row of a matrix with the minimum sum of its elements.

Problem Statement:

Given a 2D matrix of integers, identify the row which has the smallest sum of its elements.

Example:

For the matrix:

matrix = [ [1, 2, 3], [4, 5, 6], [-1, -2, -3] ] 

The sums for each row are:

[6, 15, -6] 

Thus, the third row ([-1, -2, -3]) has the minimum sum of -6.

Tutorial:

1. Using List Comprehension:

List comprehension provides a concise way to process lists.

def row_with_min_sum(matrix): sums = [sum(row) for row in matrix] return matrix[sums.index(min(sums))] # Example usage: matrix = [ [1, 2, 3], [4, 5, 6], [-1, -2, -3] ] print(row_with_min_sum(matrix)) # Output: [-1, -2, -3] 

Explanation:

  • We compute the sum for each row using list comprehension.
  • We use the index method to get the index of the row with the smallest sum and then return that row.

2. Using For Loops:

For those who prefer a more explicit approach, nested loops can be used:

def row_with_min_sum(matrix): min_sum = float('inf') min_sum_row = None for row in matrix: current_sum = sum(row) if current_sum < min_sum: min_sum = current_sum min_sum_row = row return min_sum_row # Example usage: matrix = [ [1, 2, 3], [4, 5, 6], [-1, -2, -3] ] print(row_with_min_sum(matrix)) # Output: [-1, -2, -3] 

Conclusion:

Finding the row with the minimum sum in a matrix is straightforward using Python. Depending on one's coding style and preference for readability, you can opt for a concise approach using list comprehensions or a more traditional method with loops. Both methods effectively employ the built-in sum function to compute the sum of elements in each row.


More Tags

shader winrm mule-component internet-explorer unsubscribe chatbot datatrigger flutter razor-pages sharepoint-2010

More Programming Guides

Other Guides

More Programming Examples