我试图实现鸿沟并征服矩阵乘法(8个递归版本而不是Strassen)。我以为我已经弄明白了,但它产生了奇怪的输出,有太多的嵌套列表和错误的值。我怀疑问题是我如何总结8次递归,但我不确定。
def multiMatrix(x,y):
n = len(x)
if n == 1:
return x[0][0] * y[0][0]
else:
a = [[col for col in row[:len(row)/2]] for row in x[:len(x)/2]]
b = [[col for col in row[len(row)/2:]] for row in x[:len(x)/2]]
c = [[col for col in row[:len(row)/2]] for row in x[len(x)/2:]]
d = [[col for col in row[len(row)/2:]] for row in x[len(x)/2:]]
e = [[col for col in row[:len(row)/2]] for row in y[:len(y)/2]]
f = [[col for col in row[len(row)/2:]] for row in y[:len(y)/2]]
g = [[col for col in row[:len(row)/2]] for row in y[len(y)/2:]]
h = [[col for col in row[len(row)/2:]] for row in y[len(y)/2:]]
ae = multiMatrix(a,e)
bg = multiMatrix(b,g)
af = multiMatrix(a,f)
bh = multiMatrix(b,h)
ce = multiMatrix(c,e)
dg = multiMatrix(d,g)
cf = multiMatrix(c,f)
dh = multiMatrix(d,h)
c = [[ae+bg,af+bh],[ce+dg,cf+dh]]
return c
a = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]
]
b = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]
]
print multiMatrix(a,b)
答案 0 :(得分:1)
您的怀疑是正确的,您的矩阵仍然是列表,因此添加它们只会列出更长的列表。
尝试使用类似的东西
def matrix_add(a, b):
return [[ea+eb for ea, eb in zip(*rowpair)] for rowpair in zip(a, b)]
代码。
加入块:
def join_horiz(a, b):
return [rowa + rowb for rowa, rowb in zip(a,b)]
def join_vert(a, b):
return a+b
最后,为了让它全部协同工作,我认为你必须改变1的特殊情况
return [[x[0][0] * y[0][0]]]
编辑:
我刚刚意识到这只适用于二维幂。否则你将不得不处理非方形矩阵,x
是1 x的东西,而你的特殊情况不会起作用。因此,您还必须检查len(x [0])(如果n> 0)。