简体   繁体   中英

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, 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. 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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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