Question

I came across a post in SO where the algorithm is implemented in python code .This is a direct implementation of the pseudocode in this article .

However,in the pseudocode ,there is a line where count is incremented by the number of remaining elements in array 'a'.In the above python code,it is given as

count += len(a) - i

can't we do the same by

count += len(a[i:])

Also,instead of

c += a[i:] + b[j:]

I wrote,

c.append(a[i:])
c.append(b[j:])

In total my version looks like this

def merge(left,right):
    i=0
    j=0
    count=0
    c=[]
    while i<len(left) and j<len(right):
        c.append(min(left[i],right[j]))
        if right[j]< left[i]:
            count+=len(left[i:])
            j+=1
        else:
            i+=1
    c.append(left[i:])
    c.append(right[j:])
    return count,c


def dnc(input):
    if len(input)==1:
        return 0,input
    mid=len(input)/2
    left=input[:mid]
    right=input[mid:]
    l,left=dnc(left)
    r,right=dnc(right)
    m,result=merge(left,right)
    count=l+r+m
    return count,result

Alas!,when I compute this on a sorted array,I get 3 instead of 0

if __name__=='__main__':
    input =[1,2,3,4,5]
    ct,res=dnc(input)
    print ct

What have I done wrong? can someone help me find out?

Was it helpful?

Solution

Here's what I can suggest:

  • Don't do count += len(a[i:]). It's slower than your original and is unnecessarily complicating the logic. I would instead cache len(a) as len_a and calculate it once outside of your loop, as a doesn't seem to be modified.

  • c += a[i:] + b[j:] is the same as c.extend(a[i:]) and c.extend(b[j:]). extend appends the contents of the list to c while append appends the list itself, which might be causing your problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top