A Matrix can be defined uniquely by a 2-dimensional list. For example,
A matrix
can be defined as [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
.
In this programming problem, you are required to define a class named Matrix
that can be used to store the information of a square matrix of size (i.e. #rows = #cols = ). Furthermore, you need to defined three methods, __add__
, __sub__
, and __mul__
, for matrix addition, subtraction, and multiplication respectively.
Please note that you should leave the original data unchanged after doing these three operations.
You can start with this template code and ensure your code can run correctly within this template:
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):
# your code here
# create a new Matrix with the value of current matrix + rhs matrix
def __add__(self, rhs):
# your code here
# create a new Matrix with the value of current matrix - rhs matrix
def __sub__(self, rhs):
# your code here
# create a new Matrix with the value of current matrix * rhs matrix
def __mul__(self, rhs):
# your code here
# output format of Matrix
def __repr__(self):
return '\n'.join([' '.join(map(str, self.m[i])) for i in range(self.size)])
# Note that the following code is for local testing purposes only. You should leave this part of code unchanged and not submit it to the OJ system.
T = int(input())
for t in range(T):
k = int(input())
m1_list = []
for _ in range(k):
m1_list.append(list(map(int, input().split())))
m2_list = []
for _ in range(k):
m2_list.append(list(map(int, input().split())))
m1 = Matrix(k, m1_list)
m2 = Matrix(k, m2_list)
print(m1+m2)
print(m1-m2)
print(m1*m2)
Please note that you only have to submit the definition of the Matrix
and its content to the OJ system. The rest of the code is for your local testing purposes only.
Input Specification
The first line of the input gives the number of test cases, , and then test cases follow.
For each test case, it will consist of a integer and two matrices, m1
and m2
. The first line contains the size of the following two matrices. And then the following lines represents the two matrices.
Constraints
Output Specification
For each test case, output three matrices which represents m1+m2
, m1-m2
, and m1*m2
respectively.
Sample Input
1
2
1 2
3 4
0 1
1 0
Sample Output
1 3
4 4
1 1
2 4
2 1
4 3
Hint
object-oriented programming
Reference
For how to multiply two matrices, you can refer to Multiplying a Matrix by Another Matrix section of this page.
Comments