Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why i don't get the maximum recursion number in python?

try:
    start = 0
    def recursion():
        global start
        def repeat():
            global start

            print('hello world')
            start += 1
            print(recursion())
            
        print(repeat())

    print(recursion())
    
except RecursionError:
    print('you eached the limit')
    print(' ')
    print('recursion :',start, 'times')

result :

hello world
hello world
you eached the limit

recursion : 497 times

Why i don’t get the maximum number of recursion in python or is this the maximum number ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The default recursion limit is 1000.

>>> sys.getrecursionlimit()
1000

A program with a single recursive function will reach 999:

start = 0

try:
    def recursion():
        global start
        start += 1
        recursion()
    recursion()
except RecursionError:
    print('recursion :', start, 'times')

prints out

recursion : 999 times

Your program is creating a stack that has recursion(), then repeat(), then recursion(), etc., and a print() call, so it makes sense you reach a bit under half of that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading