Multiply two matrices

Multiply matrix A by matrix B, if their shapes allow it.

Input

A line r c, then r lines of c whole numbers (matrix A). Then a line r2 c2 and r2 lines of c2 whole numbers (matrix B). All sizes are 1 to 10.

Output

The rows of A·B, numbers separated by single spaces. If the shapes do not fit, print cannot multiply RxC by R2xC2 with the four sizes.

Examples

Example 1 · Input
2 2
1 2
3 4
2 2
0 1
1 0
Expected output
2 1
4 3
Example 2 · Input
2 3
1 0 2
-1 3 1
3 1
3
2
1
Expected output
5
4

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

A (r1 × c1) times B (r2 × c2) works only when c1 equals r2.

Hint 2

Entry (i, j) is the sum over k of A[i][k] × B[k][j].

Solution

Show one correct solution (try it yourself first)
def read():
    r, c = map(int, input().split())
    return [[int(x) for x in input().split()] for _ in range(r)], r, c

A, r1, c1 = read()
B, r2, c2 = read()
if c1 != r2:
    print(f"cannot multiply {r1}x{c1} by {r2}x{c2}")
else:
    for i in range(r1):
        print(" ".join(str(sum(A[i][k] * B[k][j] for k in range(c1))) for j in range(c2)))

Lesson: Matrices and matrix multiplication →