|
| 1 | +from numpy import dot as dot_product |
| 2 | + |
| 3 | +def matrix_dot_vector(a: list[list[int|float]], b: list[int|float]) -> list[int|float]: |
| 4 | + if len(a) != len(b): |
| 5 | + return -1 |
| 6 | + |
| 7 | + return dot_product(a,b) |
| 8 | + |
| 9 | +def test_matrix_dot_vector() -> None: |
| 10 | + # empty product |
| 11 | + assert matrix_dot_vector([], []) == [] |
| 12 | + |
| 13 | + # invalid product |
| 14 | + assert matrix_dot_vector([], [1, 2]) == -1 |
| 15 | + assert matrix_dot_vector([[1, 2]], []) == -1 |
| 16 | + assert matrix_dot_vector([[1, 2], [2, 4]], [1]) == -1 |
| 17 | + |
| 18 | + # valid product |
| 19 | + a: list[list[int | float]] = [[1, 2], [2, 4]] |
| 20 | + b: list[int | float] = [1, 2] |
| 21 | + assert matrix_dot_vector(a, b) == [5, 10] |
| 22 | + |
| 23 | + # valid product with rectangular matrix (non-square) -- > if we changed "for j in range(len(a[i]))" to "for j in range(len(a))" previous tests will pass |
| 24 | + a: list[list[int | float]] = [[1, 2, 3], [2, 4, 6]] |
| 25 | + b: list[int | float] = [1, 2, 3] |
| 26 | + assert matrix_dot_vector(a, b) == [14, 28] |
| 27 | + |
| 28 | +if __name__ == "__main__": |
| 29 | + test_matrix_dot_vector() |
| 30 | + print("All tests passed.") |
0 commit comments