User Tools

Site Tools


python3:recursion_depth

This is an old revision of the document!


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.

python3/recursion_depth.1557252291.txt.gz · Last modified: 2019/05/07 13:04 by jguerin