Editorial for Matrix
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
class Matrix:
# size: a integer represented the size of the square matrix
# m: the matrix represented in the 2-d list format
# create a square matrix
def __init__(self, size, m):
self.size = size
self.m = m[:][:]
# create a new Matrix with the value of current matrix + rhs matrix
def __add__(self, rhs):
size = self.size
return Matrix(size, [[self.m[i][j]+rhs.m[i][j] for j in range(size)] for i in range(size)])
# create a new Matrix with the value of current matrix - rhs matrix
def __sub__(self, rhs):
size = self.size
return Matrix(size, [[self.m[i][j]-rhs.m[i][j] for j in range(size)] for i in range(size)])
# create a new Matrix with the value of current matrix * rhs matrix
def __mul__(self, rhs):
size = self.size
m = []
for i in range(size):
row = []
for j in range(size):
row.append(sum([self.m[i][k]*rhs.m[k][j] for k in range(size)]))
m.append(row)
return Matrix(size, m)
# output format of Matrix
def __repr__(self):
return '\n'.join([' '.join(map(str, self.m[i])) for i in range(self.size)])
Comments