我正在学习以下代码。
def merge(left, right, compare):
"""Assumes left and right are sorted lists and compare defines an ordering on the elements.
Returns a new sorted (by compare) list containing the same elements as (left + right) would contain."""
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if compare(left[i], right[j]):
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while (i < len(left)):
result.append(left[i])
i += 1
while (j < len(right)):
result.append(right[j])
j += 1
return result
def mergeSort(L, compare = lambda x, y: x < y):
"""Assumes L is a list, compare defines an ordering on elements of L
Returns a new sorted list with the same elements as L"""
if len(L) < 2:
return L[:]
else:
middle = len(L)//2
left = mergeSort(L[:middle], compare) # line A
right = mergeSort(L[middle:], compare) # line B
return merge(left, right, compare)
这本书让我举个例子L = [2,1,4,5,3]
然后在控制台中键入mergeSort(L),结果为[1,2,3,4,5]
我的问题在于mergeSort。
为什么&#34;离开&#34;和&#34;对&#34;应该在上述步骤之后返回一个排序列表(来自函数merge的定义)。任何人都可以详细解释#line A&amp; amp; #行B被执行?
我替换:
&#34; left = mergeSort(L [:middle],compare)&#34;进入&#34;左= mergeSort(L [:2],比较)&#34;。
但是,每当我运行mergeSort(L)时,Python总是告诉我“内核死了,重启”#39;在这次替换之后。在中间== 2的情况下,为什么输出会如此不同?当我替换“中间”时出了什么问题?成一个整数?
注意:以上所有代码均来自使用Python进行计算和编程的介绍
一书的图10.5。