Given two sparse matrices A and B, return the result of AB.
You may assume that A's column number is equal to B's row number.
Example:
A = [ [ 1, 0, 0], [-1, 0, 3] ] B = [ [ 7, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 1 ] ] | 1 0 0 | | 7 0 0 | | 7 0 0 | AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 | | 0 0 1 |
根据题意,就是线性代数的矩阵乘法。 矩阵乘法, 第i行,j列的数字,是有第一个矩阵的i行,和第二个矩阵的j列相乘,再相加得到的。
利用python的built-in function, zip, map, sum能够很快解题。
class Solution(object):
def multiply(self, A, B):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
result = []
BT = zip(*B) # transfer B,get the column of B
length = len(B)
for row in A:
if not any(row):
result.append([0] * length)
continue
result.append([sum(map(lambda (x, y): x*y, zip(row, col)))
if any(col) else 0 for col in BT])
return result
主要是zip(*B),首先*表示unpack,把B:List[List[int]]外层的list打开,变成了zip([a,,b,c], [d,e,f], [h,i,j])的样子,直接得到了矩阵的转置,即我们需要的列。
然后就是loop第一个矩阵,做乘法,累加,得到一个新的list,即我们需要的。