Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Determinant by colinmcnicholl
def get_matrix_minor(M,i,j):
"""Inputs: Matrix M and indices i and j, as integers, to select
element of M from row i and column j of M. For example:
M = [[1, 1, 0, 0],
[1, 0, 1, 0],
[1, 0, 0, 1],
[0, 1, 1, 0]]
i = 0; j = 0
matrix minor = [[0, 1, 0],
[0, 0, 1],
[1, 1, 0]]
Output: The elements of matrix M not in row i and column j.
"""
return [row[:j] + row[j + 1:] for row in (M[:i] + M[i + 1:])]
def checkio(data):
"""Input: A square matrix as a list of lists with integers.
Output: The determinant of input matrix, 'data', as an integer.
"""
if len(data) == 1: return data[0][0]
if len(data) == 2: #base case for 2x2 matrix
return data[0][0] * data[1][1] - data[0][1] * data[1][0]
determinant = 0
for c in range(len(data)):
determinant += ((-1)**c) * (data[0][c]
* checkio(get_matrix_minor(data, 0, c)))
return determinant
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio([[4, 3], [6, 3]]) == -6, 'First example'
assert checkio([[1, 3, 2],
[1, 1, 4],
[2, 2, 1]]) == 14, 'Second example'
Oct. 20, 2020