Skip to content

Instantly share code, notes, and snippets.

@jaeheonshim
Created December 12, 2021 01:42
Show Gist options
  • Save jaeheonshim/6209028df3292d1e4c9591882fe07dc5 to your computer and use it in GitHub Desktop.
Save jaeheonshim/6209028df3292d1e4c9591882fe07dc5 to your computer and use it in GitHub Desktop.
Take the determinant of a square matrix in Python
def determinant(matrix):
if len(matrix) == 1:
return matrix[0][0]
if len(matrix) == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
sign = 1
det = 0
for i in range(len(matrix)):
det += matrix[0][i] * determinant(minor(matrix, 0, i)) * sign
sign *= -1
return det
def minor(matrix, row, col):
new = [matrix[r][:] for r in range(len(matrix)) if r != row]
for i in range(len(new)):
new[i].pop(col)
return new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment