Python - Row with Maximum Product

Python - Row with Maximum Product

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

Problem Statement:

Given a 2D matrix of integers, find the row which has the maximum product of its elements.

Example:

For the matrix:

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

The row-wise products are:

[6, 6, 8] 

Thus, the third row ([4, 2, 1]) has the maximum product of 8.

Tutorial:

1. Using List Comprehension:

List comprehension is a concise way to process lists.

def row_with_max_product(matrix): products = [eval('*'.join(map(str, row))) for row in matrix] max_product_index = products.index(max(products)) return matrix[max_product_index] # Example usage: matrix = [ [1, 2, 3], [-1, -2, 3], [4, 2, 1] ] print(row_with_max_product(matrix)) # Output: [4, 2, 1] 

Explanation:

  • We calculate the product for each row using a combination of eval and join.
  • Then, we find the index of the maximum product and return the corresponding row.

2. Using For Loops:

For those who find the above approach a bit tricky, a more explicit method can be applied using loops.

def row_with_max_product(matrix): max_product = float('-inf') max_product_row = None for row in matrix: product = 1 for num in row: product *= num if product > max_product: max_product = product max_product_row = row return max_product_row # Example usage: matrix = [ [1, 2, 3], [-1, -2, 3], [4, 2, 1] ] print(row_with_max_product(matrix)) # Output: [4, 2, 1] 

Conclusion:

Identifying the row with the maximum product in a matrix is straightforward with Python. You can either opt for a concise approach using list comprehensions or a more straightforward loop-based method. Both methods are effective; the choice depends on one's coding style and readability preference.


More Tags

ag-grid-angular command-prompt linux pre-commit reducers ssms hyper-v viewpropertyanimator spring-test-mvc

More Programming Guides

Other Guides

More Programming Examples