Python - Maximum of each Column

Python - Maximum of each Column

In this tutorial, we'll learn how to find the maximum value of each column in a matrix (2D list) in Python.

Problem Statement:

Given a 2D list (matrix) mat of integers, determine the maximum value in each column.

Example:

Input:

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

Output:

Maximum of each column: [5, 9, 6] 

Step-by-Step Solution:

  1. Initialize Result List: Create a list max_values to store the maximum value for each column.
  2. Traverse Each Column: Use a loop to traverse each column.
  3. Compute Maximum for Current Column: For each column, compute the maximum value and append it to max_values.
  4. Return Result: Return the max_values list.

Here's how to implement the solution:

def max_of_each_column(mat): # Step 1: Initialize Result List max_values = [] # Step 2: Traverse Each Column for col in range(len(mat[0])): # Assuming all rows have the same number of columns # Step 3: Compute Maximum for Current Column column_max = max(row[col] for row in mat) # Append to the result list max_values.append(column_max) # Step 4: Return Result return max_values # Test mat = [ [3, 7, 2], [5, 8, 4], [1, 9, 6] ] print("Maximum of each column:", max_of_each_column(mat)) # Expected Output: Maximum of each column: [5, 9, 6] 

Explanation:

For the matrix mat given above:

  • The maximum value in the first column is 5 (from the numbers 3, 5, 1).
  • The maximum value in the second column is 9 (from the numbers 7, 8, 9).
  • The maximum value in the third column is 6 (from the numbers 2, 4, 6).

The solution uses a loop to traverse each column and a generator expression to compute the maximum value of each column. The time complexity of the solution is O(m*n) where m is the number of rows and n is the number of columns in the matrix.


More Tags

maven-surefire-plugin search django-2.0 cross-site baasbox wp-api persistence post-install whatsapi ip-address

More Programming Guides

Other Guides

More Programming Examples