Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if permutations have equal parity?

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.

like image 503
Ashwin Nanjappa Avatar asked Oct 01 '09 10:10

Ashwin Nanjappa


People also ask

What do we have to check to ensure that the parity of a permutation is well defined?

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).

How do you know if a permutation is even?

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.

Which permutation is an even permutation?

The Identity permutation is an even permutation.


1 Answers

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
like image 179
jfs Avatar answered Sep 21 '22 12:09

jfs