MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / inverse

Function inverse

matrix/matrix_operation.py:141–162  ·  view source on GitHub ↗

>>> inverse([[1, 2], [3, 4]]) [[-2.0, 1.0], [1.5, -0.5]] >>> inverse([[1, 1], [1, 1]])

(matrix: list[list[int]])

Source from the content-addressed store, hash-verified

139
140
141def inverse(matrix: list[list[int]]) -> list[list[float]] | None:
142 """
143 >>> inverse([[1, 2], [3, 4]])
144 [[-2.0, 1.0], [1.5, -0.5]]
145 >>> inverse([[1, 1], [1, 1]])
146 """
147 # https://stackoverflow.com/questions/20047519/python-doctests-test-for-none
148 det = determinant(matrix)
149 if det == 0:
150 return None
151
152 matrix_minor = [
153 [determinant(minor(matrix, i, j)) for j in range(len(matrix))]
154 for i in range(len(matrix))
155 ]
156
157 cofactors = [
158 [x * (-1) ** (row + col) for col, x in enumerate(matrix_minor[row])]
159 for row in range(len(matrix))
160 ]
161 adjugate = list(transpose(cofactors))
162 return scalar_multiply(adjugate, 1 / det)
163
164
165def _check_not_integer(matrix: list[list[int]]) -> bool:

Callers 1

mainFunction · 0.85

Calls 4

determinantFunction · 0.85
minorFunction · 0.85
scalar_multiplyFunction · 0.85
transposeFunction · 0.70

Tested by

no test coverage detected