Python 递归意外停止

标签 python recursion graph

简单地说,虽然其他一切都很好,但递归中途停止了。

递归函数如下所示(完整代码见here):

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. 所有失败的递归都到达检查点1但未能到达检查点2,并且递归根本不执行;
  3. 它根本没有达到最大递归时间,我已将最大递归时间设置为 sys.setrecursionlimit(10**6)
  4. 它在相对较小的输入(数百或数千个节点)上运行得很好,但在拥有超过 800,000 个节点的大图上却卡住了。

这让我发疯,我看不出它不起作用的原因,没有错误,没有堆栈溢出,只是停止了,说按任意键继续...为如果完成了。有人知道可能出什么问题吗?

最佳答案

documentation指定:

The highest possible limit is platform-dependent. A user may need to set the limit higher when they have a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.

有一个script检查该限制。

您必须实现非递归 DFS。

关于Python 递归意外停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48656094/

相关文章:

Java-构建一个用零替换偶数的递归

从切割顶点找到桥梁的算法

r - R中的绘图列表结构

python - 使循环依赖模型属性在 graphene-django 中可查询

python - 如何获取 ffprobe 元数据作为变量在 python 中解析

python - 如何正确格式化QCompleter弹出列表的列表项?

java - 在图表上放置正确的刻度标记

python - 将正弦应用于矩阵的快速方法

swift - BAD_ACCESS 在 Swift 递归调用期间

python - threading.Timer如何避免Python中的递归?