Skip to content

Matrix Trace

Background

The trace of a square matrix is defined as the sum of elements on the main diagonal (from the upper left to the lower right).

Task

Write a function matrix_trace(mat) that computes the trace of a given square matrix.

Specifications

  • The function takes a 2D list mat.
  • It returns a single number representing the trace.

Constraints

  • The input matrix will be square ($N \times N$).
  • $N \ge 1$.

Example

>>> matrix_trace([[1, 2], [3, 4]])
5

Instructions

  1. Implement the logic in solution.py.
  2. Do not use input() or print().
  3. Test your solution locally before submitting.

Solve Online | Ver en Español, | Leer en Español