Dribbler
Dribbler

Reputation: 4701

Syntax for recursion in a Python class

I'm learning Python and am grappling with the syntax of self in a class. With this code

class Matrix( object ):

    def __init__( self, arrays ): # expects array of array
        self.arrays = arrays
        self.num_columns = len( self.arrays[ 0 ] )

    def get_num_cols( self ):
        return self.num_columns

    def get_minor( self, r1, r2 ):
        return [ row[ :r2 ] +  row[ r2 + 1: ] for row in ( self.arrays[ :r1 ] + self.arrays[ r1 + 1: ] ) ] 

    def determinant( self ):

        determinant = 0
        for c in range( self.get_num_cols() ):
            determinant += ( ( -1 ) ** c ) * self.arrays[ 0 ][ c ] * self.determinant( self.get_minor( 0, c ) )

        return determinant

It's choking on

...self.determinant( self.get_minor( 0, c ) )

And I understand why--the determinant method expects just self and is getting another argument. Not encapsulated in a class the code (without self) works fine, but in a class I need to use that pesky self. In C++, I would just be working on the underlying data structures. So I basically see what the problem is, but I can't see a solution. Can anyone help with using this kind of recursion in a Python class?

Thanks in advance!

Upvotes: 0

Views: 91

Answers (1)

Dan D.
Dan D.

Reputation: 74685

self.determinant( self.get_minor( 0, c ) )

should likely be:

Matrix(self.get_minor( 0, c )).determinant()

This turns the nested lists that get_minor returns into a Matrix and then calls its determinant method. If get_minor returned a Matrix the code would be:

self.get_minor( 0, c ).determinant()

Upvotes: 4

Related Questions