Advanced · 2D lists · 176 of 264
Matrix multiplication
Multiply an n by m matrix A by an m by p matrix B.
Input: n m p, then n lines of A, then m lines of B. Output: the n by p product.
Examples
Input
2 2 2 1 2 3 4 5 6 7 8
Output
19 22 43 50
Input
1 3 1 1 2 3 4 5 6
Output
32
One more test checks other inputs when you press Check.
Stuck? The idea behind 2d lists
A list of lists is a grid: grid[row][col]. Read one row per line, each turned into numbers.
Loop over rows, then over the columns inside each row. zip(*grid) turns rows into columns.
grid = [[1, 2, 3], [4, 5, 6]]
for row in grid:
print(*row)
print(grid[1][2]) # 6Watch for: [[0] * 3] * 2 makes two names for the same row: changing one changes both. Build rows with a comprehension: [[0] * 3 for _ in range(2)].