User Tools

Site Tools


python3:recursion_depth

Recursion Depth Limits

Factorial

The factorial function is a canonical recursive example. Factorial has a convenient recursive definition as n! = n * (n – 1)! where 0! = 1! = 1.

The following is a standard implementation derived from this definition:

factorial.py
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)
 
print(factorial(997))

In the above example n=997 was chosen because any larger will cause the system to throw an exception: RecursionError: maximum recursion depth exceeded in comparison.

A trivial modification will reset the system recursion limit.

factorial_deep.py
import sys
 
sys.setrecursionlimit(2000)
 
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)
 
print(factorial(1997))

Note that n=1997 reflects the new maximum recursion depth in this example.

Safety

Note that the official Python3 documentation describes an implicit danger in this function, with little guidance as to safe use other than a “platform-dependent” limit.1) Exceeding this limit will lead to a crash.

1)
I.e., It is unlikely that this is a good idea in most/all production settings.
python3/recursion_depth.txt · Last modified: 2019/05/07 13:10 by jguerin