0

For example, when writing some algorithms on graphs like

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)

limited depth of recursion is sometimes very annoying, because code becomes much longer and more complicated if you have to avoid recursion. Is there a way to reach unlimited depth? Maybe you can describe your general solution of the problem on the following method

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

(I know it's simple stupid and please don't give answers like "You should have written just nthNumber(n): return n " - I'm intrested in general solution). Thanks for help!

Antoine
  • 862
  • 7
  • 22
  • Let me put in another way: is it possibly to make a recurison method with max. depth 10**4 or 10**5? – Antoine Apr 20 '13 at 20:47
  • You can set the recursion limit to 10**4, but you may end up crashing python (it is probably over the safe limit - which is OS dependent). Also : http://stackoverflow.com/questions/2917210/python-what-is-the-hard-recursion-limit-for-linux-mac-and-windows – root Apr 20 '13 at 20:52

1 Answers1

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().

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 2
    **Unlimited != Infinite**, What he was asking for is un'limited', meaning Python wouldn't enforce any limits on this. – nehem May 04 '16 at 06:33
  • 2
    @itsneo: that's just... splitting hairs. You can raise the limit to beyond what the OS or available hardware would allow. The point is that you'll run into *a* limit. – Martijn Pieters May 04 '16 at 10:11