Multiplying a matrix by a vector is the basic action of a matrix: it turns one vector into another.
What to build
Multiply an r × c matrix by a vector of c numbers and print the resulting vector.
Requirements
- Read the matrix size, the matrix rows and the vector.
- Entry i of the result is the dot product of row i and the vector.
- Print the r numbers separated by single spaces.
Input
Line 1: r and c (1 to 6). Then r lines of c whole numbers. Then one line of c whole numbers.
Output
One line with r whole numbers separated by spaces.
Constraints
All entries are between -100 and 100.
Example
Input:
2 2
1 2
3 4
1 1
Output:
3 7
Why it works
Each output entry combines one row of the matrix with the whole vector through a dot product. This is the row-times-column rule when the second matrix has only one column.
Examples
2 2 1 2 3 4 1 1
3 7
2 3 1 0 2 0 1 -1 3 4 5
13 -1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Each output entry is the dot product of one row of the matrix with the vector.
Hint 2
Read r and c first, then r rows, then the vector with c entries.
Hint 3
Print the result as one line of whole numbers.
Solution
Show one correct solution (try it yourself first)
r, c = [int(x) for x in input().split()] A = [[int(x) for x in input().split()] for _ in range(r)] v = [int(x) for x in input().split()] print(*[sum(a * b for a, b in zip(row, v)) for row in A])
▶ Open this solution in the compiler, then press Visualize to watch it run step by step