""" determinants.py recursively find determinant of an N x N (size x size) matrix, where the matrix is stored as a 1D list of numbers. This will translate into C directly, *except* (1) size must be given as an argument explicitly, since C has no len() function and cannot determine the length of an (int*) (2) in cofactor, we must allocate memory explicitly with malloc or calloc, instead of [0]*() """ from math import sqrt def cofactor(matrix, co_row, co_column): """ Return the smaller matrix that you get by keeping only the numbers *not* in co_row or co_column as row=0, column=i """ size = int(sqrt(len(matrix))) result = [0] * ((size-1)*(size-1)) # loop through the matrix i = 0 for row in range(size): for column in range(size): # only copy elements *not* in given row,column if row != co_row and column != co_column: result[i] = matrix[row*size + column] i += 1 return result def determinant(matrix): """ Return determinant of list of n*n numbers """ print " Finding determinant({})".format(matrix) if len(matrix) == 1: return matrix[0] else: size = int(sqrt(len(matrix))) sign = 1 # alternate signs result = 0.0 for i in range(size): # i = 0, 1, ... (size-1) co_matrix = cofactor(matrix, co_row=0, co_column=i) result += matrix[i] * sign * determinant(co_matrix) sign = -1 * sign return result def main(): matrix = [1, 2, 3, 4, 1, -1, 6, -2, -3] answer = determinant(matrix) print "answer is {}".format(answer) main()