19 Jul 2013

Determinant行列式求值

收藏到CSDN网摘


矩阵行列式的求值

def minor(x,i,j):
    # 
    y = x[:]
    del(y[i-1])
    y=zip(*y)
    del(y[j-1])
    return zip(*y)

def det(x):
    # determinant of a square matrix
    l = len(x)
    if l == 1:
        return x[0][0]
    return sum([(-1)**i*x[i][0]*det(minor(x,i+1,1)) for i in range(l)])

def checkio(data):
    return det(data)

#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    assert checkio([[4,3], [6,3]]) == -6, 'First example'

    assert checkio([[1, 3, 2],
                    [1, 1, 4],
                    [2, 2, 1]]) == 14, 'Second exam'

1 comment :