我写以下合并排序代码:IndexError:弹出索引超出范围(蟒)
def merge_sort(self,a):
#console.log(len(a))
if len(a) <= 1:
return a
left = []
right = []
result = []
middle = int(len(a)/2)
print middle
left = a[:middle] #set left equal to the first half of a
right = a[middle:] #set right equal to the second half of a
print left
print right
left = self.merge_sort(left)
right = self.merge_sort(right)
result = self.merge(left, right)
return result
然后合并的代码:
def merge(self, left, right):
result = []
while len(left) > 0 or len(right) > 0:
if len(left) > 0 and len(right) > 0:
if left[0] <= right[0]:
result.append(left[0])
left = left.pop(1) #remove the first element from left
elif len(left) > 0:
result.append(left[0])
left = left.pop(1) #remove the first element from left
elif len(right) > 0:
result.append(right[0])
right = right.pop(1) #remove the first element from right
else:
result.append(right[0])
right = right.pop(1)
return result
我发送的数组: 一个= [ 12,0,232]
我得到以下输出(不同的迭代),并在最后输出我得到的错误,请帮助我不明白为什么错误在那里谢谢你!:
(1 [12] [0,232]) (1 [0] [232])
回溯(最近最后调用): ... \ Sort_Class.py” ,第116行,合并 left = left.pop(1)#从左边移除第一个元素 IndexError:弹出索引超出范围
如果'left'比2项短,那么你会得到这个错误。 –