Created
April 29, 2020 01:19
-
-
Save DominikPeters/211aa0eb89599189c6d18286142ec15e to your computer and use it in GitHub Desktop.
Compute Cayley distance between two rankings
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
# for two permutations of [0,1,...,n], compute how many swaps (not necessarily adjacent) | |
# are needed to transform one into the other | |
# code uses: distance of a permutation from the identity permutation | |
# equals n - #cycles in the cycle notation of the permutation | |
def cayley_distance(x,y): | |
A = range(len(x)) | |
inv_y = tuple(y.index(a) for a in A) | |
comp = tuple(x[inv_y[a]] for a in A) | |
cycles = 0 | |
rem = set(A) | |
while rem: | |
a = rem.pop() | |
cycles += 1 | |
while comp[a] in rem: | |
a = comp[a] | |
rem.remove(a) | |
return len(A) - cycles | |
assert cayley_distance([0,1,2,3],[1,0,2,3]) == 1 | |
assert cayley_distance([0,1,2,3],[1,0,3,2]) == 2 | |
assert cayley_distance([2,1,3,0],[0,3,1,2]) == 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment