0

例如,在像这样的图上编写一些算法时

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)

有限的递归深度有时很烦人,因为如果你不得不避免递归,代码会变得更长更复杂。有没有办法达到无限深度?也许您可以通过以下方法描述您对问题的一般解决方案

def nthNumber(n):
    if n==1: return 1
    else: return nthNumber(n-1)+1

(我知道这很愚蠢,请不要给出“你应该只写 nthNumber(n): return n ”之类的答案——我对一般解决方案很感兴趣)。感谢帮助!

4

1 回答 1

7

Unlimited recursion would require infinite resources; every function call requires a stack entry, and there is only a finite amount of memory to hold those. So, no, you cannot have unlimited recursion depth.

You can raise the limit, by calling sys.setrecursionlimit().

于 2013-04-20T20:45:25.587 回答