Skip to content

Instantly share code, notes, and snippets.

@shiracamus
Created April 7, 2019 10:05
Show Gist options
  • Save shiracamus/3ff8fb20d149ea5a9b0999742fcb388b to your computer and use it in GitHub Desktop.
Save shiracamus/3ff8fb20d149ea5a9b0999742fcb388b to your computer and use it in GitHub Desktop.
from pprint import pprint
def sign(i):
return (+1, -1)[i & 1]
def cof(matrix, y, x):
return [[value for c, value in enumerate(row) if x != c]
for r, row in enumerate(matrix) if y != r]
def det(matrix):
if len(matrix) == 1:
return matrix[0][0]
else:
return sum(sign(y) * row[0] * det(cof(matrix, y, 0))
for y, row in enumerate(matrix))
def trans(matrix):
return list(zip(*matrix))
def inv(matrix):
d = det(matrix)
c = [[sign(y+x) * det(cof(matrix, y, x)) / d
for x, _ in enumerate(row)]
for y, row in enumerate(matrix)]
t = trans(c)
return t
A = [[2, 1, 1], [0, -2, 1], [0, -1, -1]]
pprint(inv(A))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment