Counting Inversions Using Merge Sort [closed]

喜夏-厌秋 提交于 2019-12-02 01:35:39

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

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)

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

Instead of

return lis

do

return lis, count

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