Search code examples
pythonmatrixlinear-algebra

How to find determinant of matrix using python


New at python and rusty on linear Algebra. However, I am looking for guidance on the correct way to create a determinant from a matrix in python without using Numpy. Please see the snippet of code below. Any assistance is greatly appreciated.

import math 
from math import sqrt
import numbers 
import operators

def determinant(self)

        if not self.is_square():
            raise(ValueError, "Cannot calculate determinant of non-square matrix.")
        if self.h > 2:
            raise(NotImplementedError, "Calculating determinant not implemented for matrices larger than 2x2.")


        |x| = A

    det(A) = [[A, B][C, D]]

    assert self.rows == A.cols
    assert self.row > 1
    term_list = []

Solution

  • sum is an inbuilt function and cannot be used as a variable name. The code was not properly indented. This should work:

    def determinant(matrix, mul):
    
        width = len(matrix)
        if width == 1:
            return mul * matrix[0][0]
        else:
            sign = -1
            answer = 0
            for i in range(width):
                m = []
                for j in range(1, width):
                    buff = []
                    for k in range(width):
                        if k != i:
                            buff.append(matrix[j][k])
                    m.append(buff)
                sign *= -1
                answer = answer + mul * determinant(m, sign * matrix[0][i])
        return answer
    
    test_matrix = [[3,2,-3],[7,-1,0],[2,-4,5]]
    
    print(determinant(test_matrix, 1))