python有一个默认的最大递归深度,我可以增加:
import sys
sys.setrecursionlimit(100000)
我使用合并排序,当我在80000个元素列表上尝试时,python"意外退出"。这不是迭代地实现合并排序的问题,但我对递归的感兴趣。
我使用的是Mac OSX 8GB内存。有没有办法让它在我的机器上运行,或者它能在更好的机器上运行吗?
import sys
sys.setrecursionlimit(100000) # python has a recurison depth of < 1000~. so for the purpose of this assignment I'm increasing it
counter = 0
def merge_sort(lst):
global counter
if len(lst) <= 1:
counter += 1 # increment counter when we divide array in two
return lst
mid = len(lst) // 2
left = merge_sort(lst[:mid])
right = merge_sort(lst[mid:])
return merge(left, right)
def merge(left, right):
global counter
if not left:
counter += 1 # increment counter when not left (not left - is also comparison)
return right
if not right:
counter += 1 # the same as above for right
return left
if left[0] < right[0]:
counter += 1 # and the final one increment
return [left[0]] + merge(left[1:], right)
return [right[0]] + merge(left, right[1:])
lines = [line.rstrip('\n') for line in open('words.txt')]
当我在40000上尝试上述操作时,它可以工作并对列表进行排序:
print(merge_sort(lines[0:40000]))
但是在50000或以上它不会。 .txt文件中的单词总数约为80000
我收到的消息:
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
答案 0 :(得分:3)
问题来自你的merge(left, right)
实现,它在O(n)中是递归的。您可以在每个递归步骤中将两个排序列表合并一个元素。在优化尾递归的语言but it is not the case in python中,合并递归的想法可能有意义。
通常,合并是迭代的,因为它的复杂性始终至少是要合并的元素的数量。
def merge(left, right):
merged = []
i = 0
j = 0
while i < len(left) and j < len(right) :
if left[i] < right[j]:
merged.append(left[i])
i+=1
else:
merged.append(right[j])
j+=1
merged += left[i:]
merged += right[j:]
return merged