[英]Syntax for recursion in a Python class
我正在學習Python,並且正在嘗試在類中使用self的語法。 有了這個代碼
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
令人窒息
...self.determinant( self.get_minor( 0, c ) )
而且我理解為什么-行列式方法只期望自我,並引起另一個爭論。 沒有封裝在類中的代碼(沒有self)可以正常工作,但是在類中,我需要使用該討厭的self。 在C ++中,我將只研究基礎數據結構。 因此,我基本上看到了問題所在,但看不到解決方案。 任何人都可以幫助在Python類中使用這種遞歸嗎?
提前致謝!
self.determinant( self.get_minor( 0, c ) )
應該可能是:
Matrix(self.get_minor( 0, c )).determinant()
這會將get_minor
返回的嵌套列表轉換為Matrix
,然后調用其determinant
方法。 如果get_minor
返回一個Matrix
則代碼為:
self.get_minor( 0, c ).determinant()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.