Ant*_*ine 0 python recursion infinite depth
例如,在图形上编写一些算法时
def f(graph):
#graph is dictionary of pairs vertex_i:{set of edges (i,j)} for 1<=i,j<=n
def g(vertex):
for vertex1 in graph:
do sth
...
for (i,j) in graph[vertex1]:
...
g(j)#recursive call
...
return ...
return g(1)
Run Code Online (Sandbox Code Playgroud)
有限的递归深度有时非常烦人,因为如果必须避免递归,代码会变得更长,更复杂.有没有办法达到无限深度?也许您可以通过以下方法描述问题的一般解决方案
def nthNumber(n):
if n==1: return 1
else: return nthNumber(n-1)+1
Run Code Online (Sandbox Code Playgroud)
(我知道这很简单,请不要回答"你应该只写nthNumber(n):返回n" - 我对一般解决方案感兴趣).感谢帮助!
无限递归需要无限的资源; 每个函数调用都需要一个堆栈条目,并且只有有限的内存来保存它们.所以,不,你不能拥有无限的递归深度.
您可以 通过致电提高限额sys.setrecursionlimit().