python - Counting Inversions Using Merge Sort -
i have made merge sort programme in python , running have modified count number of inversions involved , giving me error :
here's code:
def merge_list(left,right,c): result=[] i,j=0,0 while < len(left) , 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] , i<j: c=c+1 result=result+left[i:] result=result+right[j:] print "inversions: ",c homecoming result,c def sort_and_count(lis,count): if len(lis)<2: homecoming 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 homecoming 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 traceback:
traceback (most recent phone 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 1 value unpack
where going wrong approach?
this line:
return lis
this problem, because expecting sort_and_count
homecoming tuple containing 2 values, when returns 1 value have problem tuple unpacking in lines left,c1=sort_and_count(lis[:middle],count)
. line should homecoming 2 values, lastly line of method:
return m,c
python algorithm sorting mergesort
No comments:
Post a Comment