Last active
December 6, 2018 00:32
-
-
Save kenjisato/88c0c943f6eb1142d877a6b9daccca63 to your computer and use it in GitHub Desktop.
Sign of a permutation
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
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 | |
if __name__ == "__main__": | |
assert sgn([1, 0, 2]) == -1 | |
assert sgn([2, 1, 0, 3]) == -1 | |
assert sgn([1, 2, 0, 3]) == 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment