我收到此错误:
Traceback (most recent call last):
File "Lab1.py", line 24, in <module>
b = mergesort(a)
File "Lab1.py", line 19, in mergesort
left = mergesort(lst[:middle])
File "Lab1.py", line 21, in mergesort
return merge(left, right)
File "Lab1.py", line 12, in merge
result.append(right[j])
IndexError: list index out of range
...在此代码上:
def merge(left, right):
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
j += 1
result.append(right[j])
return result
def mergesort(lst):
if len(lst) <= 1:
return lst
middle = int(len(lst) / 2)
left = mergesort(lst[:middle])
right = mergesort(lst[middle:])
return merge(left, right)
a = [3,1,2,5,9,6,7]
b = mergesort(a)
print('Input #1: ' + ', '.join(str(x) for x in a))
print('Output #1: ' + ', '.join(str(x) for x in b))
我正在使用Python 3.3.2。