Skip to content

Instantly share code, notes, and snippets.

@shravanasati
Created January 9, 2024 09:30
Show Gist options
  • Save shravanasati/1521720fa7eac0f6eb3bf4531b05110b to your computer and use it in GitHub Desktop.
Save shravanasati/1521720fa7eac0f6eb3bf4531b05110b to your computer and use it in GitHub Desktop.
calculate determinant of a (square) matrix
from typing import TypeVar
T = TypeVar("T", int, float)
Matrix = list[list[T]]
def is_square(matrix: Matrix):
n = len(matrix)
for row in matrix:
if len(row) != n:
return False
return True
def determinant(matrix: Matrix):
assert is_square(matrix)
n = len(matrix)
if n == 1:
return matrix[0][0]
det = 0
sign = 1
for i, major in enumerate(matrix[0]):
sub_matrix: Matrix = []
for other_row in matrix[1:]:
other_row = other_row.copy()
other_row.pop(i)
sub_matrix.append(other_row)
det += major * sign * determinant(sub_matrix)
sign *= -1
return det
if __name__ == "__main__":
m1 = [[1, 2], [3, 4]]
m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
m3 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
print(determinant(m1))
print(determinant(m2))
print(determinant(m3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment