Counting Inversions Using Merge Sort [closed]

依然范特西╮ 提交于 2019-12-20 03:51:06

问题


I have made a merge sort program in Python and it is running perfectly but I have modified it to count the number of inversions involved and now it is giving me an error :

Here's my code:

def merge_list(left,right,c):
    result=[]
    i,j=0,0
    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            result.append(left[i])
            print "Left result",result
            i=i+1
        elif left[i] > right[j]:
            result.append(right[j])
            print "Right result",result
            j=j+1
        if right[j] < left[i]  and i<j:
            c=c+1
    result=result+left[i:]
    result=result+right[j:]
    print "Inversions: ",c
    return result,c


def sort_and_count(lis,count):

    if len(lis)<2:
        return lis
    middle=len(lis) / 2
    left,c1=sort_and_count(lis[:middle],count)
    print "left",left
    right,c2=sort_and_count(lis[middle:],count)
    print "right",right
    m,c=merge_list(left,right,count)
    c=c+c1+c2
    return m,c


if __name__=="__main__":

    print "Enter 6 elements: "
    i=0;lis=[];merge_lis=[];inv=0
    while i<=5:
        x=int(raw_input())
        lis.append(x)
        i=i+1
    count=0
    merge_lis,inv=sort_and_count(lis,count)
    print "Sorted list is: ",merge_lis,inv

And my traceback:

Traceback (most recent call last):
  File "Sort_and_count.py", line 53, in <module> 
    merge_lis,inv=sort_and_count(lis,count) 
  File "Sort_and_count.py", line 31, in sort_and_count 
    left,c1=sort_and_count(lis[:middle],count) 
  File "Sort_and_count.py", line 31, in sort_and_count
    left,c1=sort_and_count(lis[:middle],count)
ValueError: need more than 1 value to unpack

Where am I going wrong with this approach?


回答1:


This line:

return lis

This is a problem, because you are expecting sort_and_count to return a tuple containing two values, so when it returns only one value you have a problem with the tuple unpacking in lines like left,c1=sort_and_count(lis[:middle],count). This line should return two values, like the last line of that method:

return m,c



回答2:


Actually, you've implemented wrong algorithm to count the number of inversions.

1) In function merge_list instead of:

elif left[i] > right[j]:
    result.append(right[j])
    print "Right result",result
    j=j+1
if right[j] < left[i]  and i<j:
    c=c+1

you should use this code:

elif right[j] < left[i]:
    result.append(right[j])
    j += 1
    inv_count += (len(left)-i)

2) Function merge_list doesn't need variable c as an input.

3) Function sort_and_count doesn't need variable count as an input.

Try this code:

def merge_list(left,right):
    result = list()
    i,j = 0,0
    inv_count = 0
    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            result.append(left[i])
            i += 1
        elif right[j] < left[i]:
            result.append(right[j])
            j += 1
            inv_count += (len(left)-i)
    result += left[i:]
    result += right[j:]
    return result,inv_count


def sort_and_count(array):
    if len(array) < 2:
        return array, 0
    middle = len(array) / 2
    left,inv_left = sort_and_count(array[:middle])
    right,inv_right = sort_and_count(array[middle:])
    merged, count = merge_list(left,right)
    count += (inv_left + inv_right)
    return merged, count





if __name__=="__main__":
    array = [2,3,1,4,5]
    merge_array,inversions = sort_and_count(array)
    print 'Start with array: %s;\nSorted array:     %s;\nInversions: %s.'%(array,merge_array,inversions)



回答3:


The error message is telling you that sort_and_count is only returning a single value. There are only two returns in the function, so the culprit is this one:

if len(lis)<2:
    return lis



回答4:


Instead of

return lis

do

return lis, count



回答5:


Well, you're returning a single value where he's expecting two.

Look at

def sort_and_count(lis,count):
    if len(lis) < 2:
        return lis
    middle = len(lis) / 2
   left, c1 = sort_and_count(lis[:middle],count)
   # etc

If you call sort_and_count([1], count), the len(lis) will be < 2 and it will return the single-element list, but will not return a count, which is expected in the call below.

Just return a value for c1 like

return lis, count # do your things with count


来源:https://stackoverflow.com/questions/14733119/counting-inversions-using-merge-sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!