import numpy as np def det(A): rows, cols = A.shape if rows == 1: return A[0][0] if rows == 2: return A[0][0]*A[1][1] - A[0][1]*A[1][0] result = 0 for i in range(rows): mat = np.zeros((rows-1, cols-1)) n = 0 for j in range(1, rows): m = 0 for k in range(cols): if k == i: continue mat[n][m] = A[j][k] m += 1 n += 1 result += ((-1)**i) * A[0][i] * det(mat) return result def adjugate(matrix): if len(matrix) == 2: res = np.zeros((2, 2)) res[0, 0] = matrix[1, 1] res[0, 1] = -matrix[0, 1] res[1, 0] = -matrix[1, 0] res[1, 1] = matrix[0, 0] return res # for matrices larger than 2x2, the same cofactor idea extends further — # we're keeping this example to a 2x2 case to stay clear and readable def inverse(A): det_A = det(A) return (1 / det_A) * adjugate(A) __ __