在python中可以捕捉无限递归的函数?

2024-04-19 17:38:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我本以为这样的问题应该得到回答,但似乎我在谷歌找不到任何解决方案。在

不管怎样。有人能给我或链接我一个内置函数,它将检查函数是否无限递归?在

一个看起来像这样的函数会很棒

def Check(InputFunction):
    if InputFunction is infinite recursing 
       print("blablla")/throw exception
    else
       run inputFunction

python中有类似的东西吗?在


Tags: 函数ifis链接defcheckexception解决方案
3条回答

这相当于问我们是否能解决停顿问题。这是做不到的。检查大量递归调用的一种方法是使用安全计数器。这是一个全局数值,每次递归调用都会递增。如果计数器达到某个非常大的值,则可以抛出错误并停止递归。在

为什么这不起作用的原因是:你有你的input_function is infinite recursing构造。现在我写下这个函数:

def paradox():
    if paradox is infinite recursing:
        return True
    else:
        return paradox()

您希望print paradox is infinite repeating的结果是什么?在

这样的程序不存在。不是在Python中,也不是在任何编程语言中。

你要的是所谓的“停顿问题”:

In computability theory, the halting problem is the problem of determining, from a description of an arbitrary computer program and an input, whether the program will finish running or continue to run forever.

参考文献:

http://en.wikipedia.org/wiki/Halting_problem

相关问题 更多 >