#380 · Classes · Advanced · 140 XP · about 30 min
Build a Matrix class that behaves like a number type, with Python's own operators.
Matrix(rows) makes a matrix from a list of rows, each a list of numbers. There must be at least one row and one column, and all rows must have the same length, otherwise raise ValueError. The matrix keeps its own copy, so changing rows afterwards does not change it.m.shape is the tuple (number of rows, number of columns).m[i, j] returns the number in row i, column j, counting from 0. Negative indexes count from the end, as with lists.a + b returns the matrix of sums of matching entries. Shapes that differ raise ValueError.a @ b returns the matrix product: entry (i, j) is the sum of a[i, k] * b[k, j] over all k. If a has a different number of columns than b has rows, raise ValueError.m ** k, for a whole number k of 0 or more, returns m multiplied by itself k times; m ** 0 is the identity matrix of the same size (1 on the diagonal, 0 elsewhere). Only square matrices have powers: otherwise raise ValueError. k can be as large as 10^18.m.transpose() returns a new matrix whose rows are the columns of m.a == b is True when the shapes and all entries are equal. A matrix is never equal to something that is not a matrix.repr(m) returns Matrix( + the list of rows + ), for example Matrix([[1, 2], [3, 4]]).a = Matrix([[1, 2], [3, 4]]) a + Matrix([[10, 20], [30, 40]]) # Matrix([[11, 22], [33, 44]]) a @ Matrix([[5], [6]]) # Matrix([[17], [39]]) a.transpose() # Matrix([[1, 3], [2, 4]]) a.shape # (2, 2) a[1, 0] # 3 Matrix([[1, 1], [1, 0]]) ** 10 # Matrix([[89, 55], [55, 34]])
First solves only, ranked by stars and then time.