This is an addition of my previous question Python matrix class. I've added a determinant function using Laplace expansion to my Matrix class. What I am looking for specifically is how 3x3 matrices are calculated, as I feel there is a better way instead of creating three matrices separately and indexing them.
class Matrix:
# ... other functions removed for brevity ...
# included for context
def __init__(self, arrays: list[list[int | float]) -> None:
self.arrays = copy.deepcopy(arrays)
self.width = len(arrays[0])
self.height = len(arrays)
def determinant(self) -> int | float:
"""
Finds the determinant of a 2x2 or a 3x3 matrix.
>>> Matrix([[4, 6], [3, 8]]).determinant()
14
>>> Matrix([[2, 7, 9], [1, 15, 4], [12, 21, 4]]).determinant()
-1171
"""
def tbtdet(m: Matrix) -> int | float:
""" 'Two By Two Determinant' => ad - bc """
return (m[0][0] * m[1][1]) - (m[0][1] * m[1][0])
if (self.width, self.height) == (2, 2):
return tbtdet(self.arrays)
if (self.width, self.height) == (3, 3):
a = Matrix([[self.arrays[1][1], self.arrays[1][2]], [self.arrays[2][1], self.arrays[2][2]]])
b = Matrix([[self.arrays[1][0], self.arrays[1][2]], [self.arrays[2][0], self.arrays[2][2]]])
c = Matrix([[self.arrays[1][0], self.arrays[1][1]], [self.arrays[2][0], self.arrays[2][1]]])
return (self.arrays[0][0] * tbtdet(a)) - (self.arrays[0][1] * tbtdet(b)) + (self.arrays[0][2] * tbtdet(c))
raise NotImplementedError("Currently only supports 2x2 and 3x3 matricies.")