简体   繁体   English

用Python实现Strassen算法的困难

[英]Difficulty in implementing Strassen's algorithm in Python

I don't understand how to call my code recursively. 我不明白如何递归调用我的代码。 Here is my code so far: 到目前为止,这是我的代码:

import numpy

B = [[5,5,5,5,5,5,5,5],[6,6,6,6,6,6,6,6],[7,7,7,7,7,7,7,7],[8,8,8,8,8,8,8,8],
 [9,9,9,9,9,9,9,9], [10,10,10,10,10,10,10,10],[11,11,11,11,11,11,11,11],       [12,12,12,12,12,12,12,12]]

A = [[5,5,5,5,5,5,5,5],[6,6,6,6,6,6,6,6],[7,7,7,7,7,7,7,7],[8,8,8,8,8,8,8,8],
 [1,1,1,1,1,1,1,1], [2,2,2,2,2,2,2,2],[3,3,3,3,3,3,3,3],[4,4,4,4,4,4,4,4]]

def main():
   strassen(A,B)

def strassen(A, B):
    A = numpy.asarray(A)
    B = numpy.asarray(B)
    lengthA = len(A)
    lengthB = len(B)
    if lengthA == 2:
        print "will calculate"
    else:       
        a, b = strassen(A[:lengthA//2, :lengthA//2], B[:lengthB//2, :lengthB//2])

        lengthA = lengthA//2
        lengthB = lengthB//2
        print a
        print b
        return a, b

I'm trying to reduce a to [[5,5],[6,6]] and b to [[5,5],[6,6]] but I'm getting an error: 我试图减少a[[5,5],[6,6]]b[[5,5],[6,6]]但我得到一个错误:

a, b = strassen(A[:lengthA//2, :lengthA//2], B[:lengthB//2, :lengthB//2])
TypeError: 'NoneType' object is not iterable. 

a and b are the 1st 2x2 matrices that will be formed after the 2nd whole matrix division for A and B. Please can someone explain this to me. ab是在对A和B进行第二次整个矩阵除法后将形成的第一2x2矩阵。请有人可以向我解释一下。 Thanks 谢谢

You have no return value in your recursion terminating condition. 您的递归终止条件中没有返回值。 When I run your code, it prints "will calculate" before giving the error. 当我运行您的代码时,它会在给出错误之前打印“将计算”。 The error happens after that because there is no return value from the strassen function on the last call (when lengthA == 2 ). 此后发生错误,因为在上一次调用时( lengthA == 2 )没有strassen函数的返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM