def parity(x):
    '''The parity of a permutation

    The parity of a permutation is even if the permutation can be
    formed by an even number of transpositions and is odd otherwise.

    The parity of a permutation is even if there are an even number of
    compositions of even size and odd otherwise. A composition is a cycle:
    for instance in (1, 2, 0, 3), there is the cycle: (0->1, 1->2, 2->0)
    and the cycle, (3->3). Both cycles are odd, so the parity is even:
    you can exchange 0 and 1 giving (0, 2, 1, 3) and 2 and 1 to get
    (0, 1, 2, 3)
    '''

    order = np.lexsort((x,))
    hit = np.zeros(len(x), bool)
    p = 0
    for j in range(len(x)):
        if not hit[j]:
            cycle = 1
            i = order[j]
            # mark every node in a cycle
            while i != j:
                hit[i] = True
                i = order[i]
                cycle += 1
            p += cycle - 1
    return 1 if p % 2 == 0 else -1
def parity ( x ) : order = np . lexsort ( ( x , ) ) hit = np . zeros ( len ( x ) , bool ) p = 0 for j in range ( len ( x ) ) : if not hit [ j ] : cycle = 1 i = order [ j ] while i != j : hit [ i ] = True i = order [ i ] cycle += 1 p += cycle - 1 return 1 if p % 2 == 0 else - 1
The parity of a permutation

    The parity of a permutation is even if the permutation can be
    formed by an even number of transpositions and is odd otherwise.

    The parity of a permutation is even if there are an even number of
    compositions of even size and odd otherwise. A composition is a cycle:
    for instance in (1, 2, 0, 3), there is the cycle: (0->1, 1->2, 2->0)
    and the cycle, (3->3). Both cycles are odd, so the parity is even:
    you can exchange 0 and 1 giving (0, 2, 1, 3) and 2 and 1 to get
    (0, 1, 2, 3)