Skip to content

Instantly share code, notes, and snippets.

@ivankahl
Created August 17, 2020 07:04
Show Gist options
  • Save ivankahl/6a19c157f762cf8a0935f79969c755b2 to your computer and use it in GitHub Desktop.
Save ivankahl/6a19c157f762cf8a0935f79969c755b2 to your computer and use it in GitHub Desktop.
Python 3 function that can be used to calculate the determinant of any n x n matrix
def det(m):
"""Returns the determinant for the n x n matrix m"""
# If the matrix is 2x2, then we just calculate the determinant
# simply otherwise we will use Laplace Expansion
if len(m) == 2:
return (m[0][0] * m[1][1]) - (m[1][0] * m[0][1])
else:
d = 0
for i in range(len(m)):
new_m = [x[0:i] + x[i+1:] for x in m[1:]]
d += (-1)**i * det(new_m)
return d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment