← back

Calculate Mean by Row or Column

#4 · Linear Algebra · Easy

⊣ Solve on deep-ml.com

Problem

Calculate the mean of a matrix either by row or by column, specified by a mode parameter ("row" or "column").

Solution

1
2
3
4
5
6
7
def calculate_matrix_mean(matrix: list[list[float]], mode: str) -> list[float]:
    if mode == "row":
        return [sum(row) / len(row) for row in matrix]
    elif mode == "column":
        num_cols = len(matrix[0])
        num_rows = len(matrix)
        return [sum(matrix[r][c] for r in range(num_rows)) / num_rows for c in range(num_cols)]

Explanation

  1. Row mode: For each row, sum all elements and divide by the row length.
  2. Column mode: For each column index, sum the elements across all rows and divide by the number of rows.

Complexity

  • Time: O(m * n)
  • Space: O(m) for row mode, O(n) for column mode