Projects/determinate3x3.py

38 lines
1.0 KiB
Python

from typing import List
import determinate2x2
import copy
def neg_odd_vals(lst: List[int])-> List[int]:
return [-val if i % 2 == 1 else val for i, val in enumerate(lst)]
def det3x3(M: List[List[int]])->int:
assert len(M) == 3 and len(M[0]) == 3, "Matrix is not 3x3"
# Matrix M with row 0 and col 0 removed
N = copy.deepcopy(M)
N[1].remove(N[1][0])
N[2].remove(N[2][0])
A = [N[1], N[2]]
#Matrix M with row 0 and col 1 removed
N = copy.deepcopy(M)
N[1].remove(N[1][1])
N[2].remove(N[2][1])
B = [N[1], N[2]]
#Matrix M with row 0 and col 2 removed
N = copy.deepcopy(M)
N[1].remove(N[1][2])
N[2].remove(N[2][2])
C = [N[1], N[2]]
# List M[0] with every odd index value set to its negative
N0 = neg_odd_vals(N[0])
# Sum of determinates A, B, C times their respective multipliers
det0 = N0[0]*determinate2x2.det2x2(A)
det1 = N0[1]*determinate2x2.det2x2(B)
det2 = N0[2]*determinate2x2.det2x2(C)
return det0 + det1 + det2