我已经在Python中制作了一个合并排序程序,并且该程序运行完美,但是我对其进行了修改,以计算涉及的反转次数,现在它给了我一个错误:
这是我的代码:
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
我的回溯:
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
这种方法在哪里出错?
这行:
return lis
这是一个问题,因为您希望sort_and_count返回一个包含两个值的元组,所以当它仅返回一个值时,您会遇到像在这样的行中对元组进行拆包的问题left,c1=sort_and_count(lis[:middle],count)。该行应返回两个值,例如该方法的最后一行:
sort_and_count
left,c1=sort_and_count(lis[:middle],count)
return m,c