Last active
December 6, 2018 00:31
-
-
Save kenjisato/b834ab0f03477ff2d147494d6699a3b3 to your computer and use it in GitHub Desktop.
Determinant of a matrix (practice)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import permutations | |
def find_a_cycle(x, start): | |
cycle = [start] | |
s = start | |
while x[s] != start: | |
cycle.append(x[s]) | |
s = x[s] | |
return cycle | |
def find_cycles(x): | |
"""find cycles in a permutation of [0, 1, ..., len(x) - 1]""" | |
cycles = [] | |
remaining = set(range(len(x))) | |
while remaining != set(): | |
start = next(iter(remaining)) | |
cycle = find_a_cycle(x, start) | |
cycles.append(cycle) | |
remaining = remaining.difference(cycle) | |
return cycles | |
def sgn(x): | |
cycles = find_cycles(x) | |
num_transpositions = sum(len(cycle) - 1 for cycle in cycles) | |
return 1 if num_transpositions % 2 == 0 else -1 | |
def det(x): | |
indices = range(len(x)) | |
total = 0 | |
for perm in permutations(indices): | |
value = sgn(perm) | |
for i, j in zip(indices, perm): | |
value *= x[i][j] | |
total += value | |
return total |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment