0

I'm trying to determine whether a permutation is odd or even by counting the transpositions from a sort. Specifically, I'd like to use the int b+c+d in the attached code so that upon calling the SortCount(A) function it will give an output of either True or False based on whether that value is odd or even.

The tuple that is returned in the included code gives the sorted array and the number of transpositions required to sort that array from it's original configuration. I'm a bit new to using tuples, and programming in general, and am not sure how to make the transposition number available to perform the stated manipulation above. Manipulating B, b+c+d from the return line for SortCount(A) breaks the code. The code is attached.

def SortCount(A):
    l = len(A)
    if l > 1:
        n = l//2
        C = A[:n]
        D = A[n:]
        C, c = SortCount(A[:n])
        D, d = SortCount(A[n:])
        B, b = MergeCount(C,D)
        return B, b+c+d
    else:
        return A, 0

def MergeCount(A,B):
    count = 0
    M = []
    while A and B:
        if A[0] <= B[0]: 
          M.append(A.pop(0)) 
        else: 
          count += len(A)
          M.append(B.pop(0)) 
    M  += A + B     
    return M, count 
Gholamali Irani
  • 4,391
  • 6
  • 28
  • 59
  • Hello, welcome to Stack Overflow! I don't think this question is appropriate to this channel... it seems to be a programming task not really an issue. – Alvaro Silvino Jan 07 '18 at 00:35
  • [This answer](https://stackoverflow.com/questions/20702782/efficiently-determine-the-parity-of-a-permutation#20703469) gives a better algorithm to find the permutation's parity. – Rory Daulton Jan 07 '18 at 00:48
  • I don't see your problem. The code seems to work. – Hennich Jan 07 '18 at 01:20
  • The code DOES work. However, I need to do more with the transposition count output from the SortCount(A) result. I want to take the b+c+d portion of that and generate a True/False Output when the function is called. I'm looking for suggestions on how to go about doing that. – Raphael Jan 07 '18 at 06:45

1 Answers1

0

this code will work fine.

def is_even(p):

    s=SortCount(p)
    return s[1]%2==0

def SortCount(p):

    l = len(p)
    if l > 1:
        n = l//2
        C = p[:n]
        D = p[n:]
        C, c = SortCount(p[:n])
        D, d = SortCount(p[n:])
        B, b = MergeCount(C,D)
        return B, b+c+d
    else:
        return p, 0

def MergeCount(p,B):

    count = 0
    M = []
    while p and B:
        if p[0] <= B[0]: 
          M.append(p.pop(0)) 
        else: 
          count += len(p)
          M.append(B.pop(0)) 
    M  += p + B     
    return M, count 
David Buck
  • 3,752
  • 35
  • 31
  • 35
Jay Shah
  • 21
  • 1
  • 4