Search code examples
python-3.xrecursionerror-handlingtail-recursionsys

Python 3 - Use of sys.setrecursionlimit()


I have written this code:

d=1
a=[d,d-1,d]
b=[]



def fctn(f):
    h=2
    if d>1:
        b.append(f)
        b.append(d-h)
    h+=1

    if d-h>0:
        fctn(f)
    elif d-h==0:
        b.append(f)
        b.append(0)
    elif d==1:
        b.append(f)

    for i in range(len(b)-1):                                  
        b.append(b[i])
    print(b)

With:

d=2

as expected, I get:

[[2, 1, 2], 0, [2, 1, 2]]    

with:

d=3

as expected, I get:

[[3, 2, 3], 1, [3, 2, 3], 0, [3, 2, 3], 1, [3, 2, 3]]

However, for d>3, I get the following error:

RecursionError: maximum recursion depth exceeded in comparison

So, I have tried to use:

sys.setrecursionlimit()

and tried to run the following code (both from IDLE and command prompt):

import sys
sys.setrecursionlimit(10**4)

d=1
a=[d,d-1,d]
b=[]



def fctn(f):
    h=2
    if d>1:
        b.append(f)
        b.append(d-h)
    h+=1

    if d-h>0:
        fctn(f)
    elif d-h==0:
        b.append(f)
        b.append(0)
    elif d==1:
        b.append(f)

    for i in range(len(b)-1):                                  
        b.append(b[i])
    print(b)    

At this point, no error arises, but output is blank. More precisely, running from IDLE I simply get:

 =============================== RESTART: Shell ===============================

So, it seems to me that the previous RecursionError has vanished, but, still, the code does not execute as I would expect, giving me essentially nothing as an output.

What's wrong with this? Also increasing the recursion limit up to 10^9 I get nothing as well. Any suggestion on how to solve the problem?


Solution

  • You are stuck in infinite recursion which is why increasing the recursion depth won't help. The problem is that you're assigning

    h=2
    

    then you

    h+=1
    

    Now h is 3 and d is 4.

    Then you get to the line:

    if d-h>0:
        fctn(f)
    

    4-3 > 0 will always be true so you'll recursively call the function again and again every time you call fctn(f) when d > 4.

    Debugging the code would have helped you find the problem. I'd suggest learning debugging if you're not already familiar with it.