Model A @ B for integer matrices, with NumPy's shape rule.
What to build
A program that multiplies two matrices.
Requirements
- If A has k columns and B has k2 rows with k ≠ k2, print
error: inner dimensions K and K2 differ. - Otherwise print A @ B in NumPy's integer format:
[[before the first row, a space and[before each later row, numbers right-aligned to the widest in the array, single spaces,]]at the end.
Input
Matrix A: a line r k and r rows. Then matrix B: a line k2 c and k2 rows.
Output
The result's rows, or one line.
Constraints
1 ≤ r, k, k2, c ≤ 10; |x| ≤ 1000.
Example
Input:
2 2
1 2
3 4
2 2
5 6
7 8
Output:
[[19 22]
[43 50]]
Why it works
Each entry of the product is a dot product of a row with a column, which only exists when a row of A is as long as a column of B.
Examples
Example 1 · Input
2 2 1 2 3 4 2 2 5 6 7 8
Expected output
[[19 22] [43 50]]
Example 2 · Input
1 3 1 2 3 3 1 4 5 6
Expected output
[[32]]
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Entry (i, j) is the dot product of row i of A with column j of B.
Hint 2
zip(*B) gives the columns of B.
Hint 3
Check that A's column count equals B's row count first.
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)]
def fmt2(m):
w = max(len(str(v)) for row in m for v in row)
rows = ["[" + " ".join(str(v).rjust(w) for v in row) + "]" for row in m]
return "[" + "\n ".join(rows) + "]"
a, b = read(), read()
if len(a[0]) != len(b):
print(f"error: inner dimensions {len(a[0])} and {len(b)} differ")
else:
cols = list(zip(*b))
print(fmt2([[sum(x * y for x, y in zip(row, col)) for col in cols] for row in a]))