Quant Python

A Matrix Class

Difficulty

Read the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.

Implement a class Matrix, a small matrix class. Do not use numpy: the task tests index discipline, shape checking and API design.

  • Matrix(rows): construct from a list of rows (lists of numbers). Store a copy, so later mutation of the input does not change the matrix.
  • matmul(other): matrix multiplication, returning a new Matrix. Raise ValueError if the inner dimensions disagree.
  • transpose(): returns a new transposed Matrix.
  • trace(): the sum of the diagonal. Raise ValueError for a non-square matrix.
  • tolist(): the contents as a plain list of lists.

Examples

Matrix([[1, 2], [3, 4]]).matmul(Matrix([[5], [6]])).tolist()
# [[17], [39]]

Matrix([[1, 2, 3], [4, 5, 6]]).transpose().tolist()
# [[1, 4], [2, 5], [3, 6]]

Methods returning new Matrix objects means calls chain, and one hidden test chains multiply and transpose. Another multiplies two 100 by 100 matrices, which pure Python handles fine if each entry is computed once.

Rate this problem
Language: Python 3.12Matrix