机器学习每日一题000-矩阵和向量的乘法python实现

题目内容

将矩阵和向量的点积计算过程用 Python 函数实现。如果操作有效,该函数应返回一个代表结果向量的列表;如果矩阵和向量的维度不兼容,则返回 -1。矩阵(一个列表的列表)只有在其列数等于向量(一个列表)的长度时,才能与该向量进行点积运算。例如,一个 n×mn \times mn×m 的矩阵需要一个长度为 mmm 的向量。

例子

Input:

a = [[1, 2], [2, 4]], b = [1, 2]

Output:

5, 10

Reasoning:

Row 1: (1 * 1) + (2 * 2) = 1 + 4 = 5; Row 2: (1 * 2) + (2 * 4) = 2 + 8 = 10

解答代码

Python List 实现

python 复制代码
def matrix_dot_vector(a: list[list[int|float]], b: list[int|float]) -> list[int|float]:

    result = []
    if len(a[0]) != len(b):
        return -1
    
    for row in a:
        dot = 0
        for i in range(len(b)):
            dot += row[i] * b[i]

        result.append(dot)

    return result

        

if __name__ == "__main__":

    a = [[1, 2], [3, 4]]
    b = [1, 2]

    print(matrix_dot_vector(a, b))
    # a = (input().strip().split())