1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def determinant(matrix):
    ''' Get the determinant of the matrix.
    :param list[list[int]] matrix: Matrix to operate on.
    :return: An integer determinant.
    Note: This only works for square matrices.
    '''
    from functools import reduce
    from itertools import permutations
    if len(matrix) != len(matrix[0]):
        raise Exception("Must be square")
    def perms(n):
        return list(permutations(range(n)))
    def sgn(l):
        count = 0
        for i in range(len(l)):
            for j in range(i + 1, len(l)):
                if l[i] > l[j]:
                    count += 1
        return 1 if (count % 2) == 0 else -1
    res = 0
    n = len(matrix)
    for perm in perms(n):
        s = sgn(perm)
        p = reduce(lambda a1, a2: a1 * a2,
                   [matrix[i][perm[i]] for i in range(n)])
        res += s * p
    return res