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.

One systematic fund's own interview-preparation guidance suggests exactly this exercise: build a small matrix class in an object-oriented language. It looks beneath a researcher's dignity until you try it under time pressure, at which point index discipline, shape checking and API design all get tested at once. No numpy here: the object is the point.

Implement a class Matrix.

  • 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: PythonMatrix
Rate this problem