0

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!

2
  • add another argument to the 'determinant' method in the class. def determinant(self, your_arg): Commented Jun 9, 2017 at 10:18
  • 1
    I don't understand the problem. You have a function that takes no arguments (other than the implicit self), and you're calling it with an argument. That doesn't work in python and it wouldn't work in C++ either. You have to make up your mind - does the determinant function take a parameter or not? Commented Jun 9, 2017 at 10:27

1 Answer 1

4
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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.