Matrix Class
Completed
Write a Matrix class supporting +, * (matrix multiplication) and transpose(), printing rows of space-separated numbers. Read two 2×2 matrices and print A + B, A × B and the transpose of A, separated by a line with --.
Input
Four lines: two rows of A, then two rows of B.
Output
The three matrices separated by --.
Example
Input
1 2 3 4 5 6 7 8
Output
6 8 10 12 -- 19 22 43 50 -- 1 3 2 4
Editor
Python
Hints
Matrix multiplication: each cell is the dot product of a row of A and a column of B.
zip(*rows) gives the columns.
Solution explanation
Operator overloading makes mathematical code read like the maths.
Show solution
class Matrix:
def __init__(self, rows):
self.rows = rows
def __add__(self, other):
return Matrix([[a + b for a, b in zip(r1, r2)] for r1, r2 in zip(self.rows, other.rows)])
def __mul__(self, other):
cols = list(zip(*other.rows))
return Matrix([[sum(a * b for a, b in zip(row, col)) for col in cols] for row in self.rows])
def transpose(self):
return Matrix([list(col) for col in zip(*self.rows)])
def __str__(self):
return "\n".join(" ".join(map(str, row)) for row in self.rows)
a = Matrix([list(map(int, input().split())) for _ in range(2)])
b = Matrix([list(map(int, input().split())) for _ in range(2)])
print(a + b)
print("--")
print(a * b)
print("--")
print(a.transpose())