I am looking for a way to check if 2 permutations (represented by lists) are of the same parity. Note that I am not interested if they are even or odd parity, just the equality.
I am new to Python and my naive solution is given below as a reply. I am looking forward to Python gurus showing me some cool tricks to achieve the same in lesser, more elegant Python code.
We show that if we multiply a permutation by a transposition from the right (i.e. first applying the transposition), then the parity of the number of cycles always changes. The number of cycles in the identity permutation is the same as the number of points n (since there are n cycles).
In practice, in order to determine whether a given permutation is even or odd, one writes the permutation as a product of disjoint cycles. The permutation is odd if and only if this factorization contains an odd number of even-length cycles.
The Identity permutation is an even permutation.
Here's slightly refactored Weeble's answer:
def arePermsEqualParity(perm0, perm1):
"""Whether permutations are of equal parity."""
return parity(combine(perm0, perm1))
def combine(perm0, perm1):
"""Combine two permutations into one."""
return map(perm0.__getitem__, perm1)
def parity(permutation):
"""Return even parity for the `permutation`."""
return (len(permutation) - ncycles(permutation)) % 2 == 0
def ncycles(permutation):
"""Return number of cycles in the `permutation`."""
ncycles = 0
seen = [False] * len(permutation)
for i, already_seen in enumerate(seen):
if not already_seen:
ncycles += 1
# mark indices that belongs to the cycle
j = i
while not seen[j]:
seen[j] = True
j = permutation[j]
return ncycles
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With