multiply two matrices together (return -1 if shapes of matrix don’t aline), i.e. C = A⋅B

Example:

  • Input:A = [[1,2],[2,4]], B = [[2,1],[3,4]]
  • Output:[[ 8, 9],[16, 18]]

这个题偷懒一下,用numpy来写,免得写for循环。

import numpy as np  
def matrixmul(a:list[list[int|float]],  
              b:list[list[int|float]])-> list[list[int|float]]:  
 A = np.array(a)  
 B = np.array(b)  
 if np.shape(A)[1] != np.shape(B)[0]:  
  return -1  
 c = A @ B  
 return c.tolist()