我在 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
这种方法哪里出错了?