我想使用以2个矩阵为参数的函数进行矩阵乘法。我的代码适用于所有测试用例,除了
mul([0, 1, 2],[[0], [1], [2]])= [0, 1, 4]
应该= [5]。知道为什么吗?
rows_A = get_rowCount(A)
cols_A = get_columnCount(A)
rows_B = get_rowCount(B)
cols_B = get_columnCount(B)
if cols_A != rows_B:
return 'Error(mul): size mismatch'
if isinstance(A[0],list) == False:
# if one is 1d and other is 2d:
if isinstance(B[0], list):
new_list = []
for i in B:
new_list.append(i[0])
B = new_list
return [a*b for a,b in zip(A,B)]
# Create the result matrix
# Dimensions would be rows_A x cols_B
C = [[0 for row in range(cols_B)] for col in range(rows_A)]
for i in range(rows_A):
for j in range(cols_B):
for k in range(cols_A):
C[i][j] += A[i][k] * B[k][j]
return C