简体   繁体   English

将python中的递归深度增加到100000

[英]increasing recursion depth in python to 100000

python has a default maximum recursion depth which I am able to increase: python有一个默认的最大递归深度,我可以增加它:

import sys

sys.setrecursionlimit(100000)

I'm using merge sort and when I try it on a list of 80000 elements, python "quits unexpectedly". 我正在使用归并排序,当我尝试对80000个元素的列表进行排序时,python“意外退出”。 This won't be an issue of I implemented merge sort iteratively, but I am interested in the recursive one. 这不是我迭代实现合并排序的问题,但是我对递归排序感兴趣。

I'm using a Mac OSX 8GB Memory. 我正在使用Mac OSX 8GB内存。 Is there a way to get this to work on my machine, or will it work on a better machine? 有没有办法让它在我的机器上工作,还是可以在更好的机器上工作?

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')]

when I try the above on a 40000 it works and sorts the list: 当我在40000上尝试上述操作时,它可以对列表进行排序:

print(merge_sort(lines[0:40000]))

but on 50000 or above it doesn't. 但是在50000或更高级别上则没有。 The total number of words in the .txt file is around 80000 .txt文件中的单词总数约为80000

the message I get: 我收到的消息:

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

The problem comes from your merge(left, right) implementation which is recursive in O(n). 问题来自您的merge(left, right)实现,该实现在O(n)中是递归的。 You merge two sorted list by one element at each recursion step. 您在每个递归步骤中将两个排序的列表按一个元素合并。 The idea of merge being recursive may make sense in languages where tail-recursion is optimized, but it is not the case in python . 递归合并的想法在优化尾递归的语言中可能是有意义的, 但在python中不是这种情况

In general, merge is iterative as its complexity will always be at least the number of elements to merge. 通常,合并是迭代的,因为其复杂度始终至少是要合并的元素数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM