Created
December 12, 2021 01:42
-
-
Save jaeheonshim/6209028df3292d1e4c9591882fe07dc5 to your computer and use it in GitHub Desktop.
Take the determinant of a square matrix in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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