Python递归停止了意外



简而言之,递归在中途停止了,尽管其他一切都很好。

递归函数如下所示(可以在此处找到整个代码(:

def DFS(graph, startNode = 0):
    global nodesProcessed; global explored; global finishingTime
    explored[startNode] = True
    currentLeader = startNode
    if startNode in graph:
        for neighbor in graph[startNode]:
            if not explored[neighbor]:
                #checkpoint 1
                DFS(graph, neighbor)
                #checkpoint 2
    else: return currentLeader
    nodesProcessed += 1
    finishingTime[startNode] = nodesProcessed
    return currentLeader

问题在于,过了一段时间后,它就停止了。让我困惑的事情是:

  1. 输入是固定的,但是停止的地方未固定。,它总是在调用的7000次左右停止;
  2. 所有失败的递归都达到了checkpoint 1,但未能达到checkpoint 2,并且递归根本没有执行;
  3. 它根本无法达到最大的递归时间,我将最大递归视为sys.setrecursionlimit(10**6)
  4. 它在相对较小的输入(数百或数千个节点(上运行良好,但粘在具有超过800,000个节点的大图上。

这让我发疯了,我看不到它不起作用,没有错误,没有堆栈溢出,只是停下来,说Press any key to continue ...就好像完成了。任何人都知道可能出了什么问题?

作为文档指定:

最高的限制是平台依赖性的。用户可能需要 当他们拥有需要深度的程序时,将极限设置为更高 递归和支持更高限制的平台。应该是 谨慎完成,因为太高的限制会导致崩溃。

有一个脚本可以检查该限制。

您将必须实现非递归DFS。

最新更新