Skip to content

Instantly share code, notes, and snippets.

@ravener
Last active October 8, 2022 18:23
Show Gist options
  • Save ravener/2582e9ca42f193567c9513b0ba1beedb to your computer and use it in GitHub Desktop.
Save ravener/2582e9ca42f193567c9513b0ba1beedb to your computer and use it in GitHub Desktop.
Calculate determinant of an n × n matrix in Python
# Get the submatrix of A
# Removing the ii-th row and jj-th column
def sub(A, ii, jj):
matrix = []
for i in range(len(A)):
if i == ii:
continue
row = A[i].copy()
row.pop(jj)
matrix.append(row)
return matrix
def det(A):
assert len(A) > 0
assert len(A) == len(A[0])
if len(A) == 1:
return A[0][0]
value = 0
sign = 1
for j in range(len(A[0])):
value += det(sub(A, 0, j)) * A[0][j] * sign
# Flip the sign for the next column
sign = -sign
return value
# 3x3 Matrix
A = [
[5, 3, 2],
[6, 1, 8],
[9, 6, 7]
]
print(det(A)) # => -61
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment