51 lines
1.6 KiB
Python
51 lines
1.6 KiB
Python
from typing import List
|
|
"""
|
|
Module for calculating the determinant of a 3x3 matrix.
|
|
Functions:
|
|
neg_odd_vals(lst: List[int]) -> List[int]:
|
|
Returns a new list where every value at an odd index is negated.
|
|
det3x3(M: List[List[int]]) -> int:
|
|
Calculates and returns the determinant of a 3x3 matrix M using Laplace expansion along the first row.
|
|
Requires an external module 'determinate2x2' with a function 'det2x2' for 2x2 determinants.
|
|
|
|
NOTE: You call determinate3x3.det3x3(M) to find the determinate of matrix M. If M is not a 3x3 matrix, you
|
|
will receive an AssertionError: "Matrix is not 3x3"
|
|
|
|
"""
|
|
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
|
|
|