2

I am finding a solution to a problem for which i have figured out the solution in c++ but when i try the same logic in python it gives out RecursionError: maximum recursion depth exceeded in comparison.

x=2
y=500

#Python Implementation

def F(x,y):
    if(x==0):
        return (y+1)%1000
    if(x>0 and y==0):
        return F(x - 1, 1)%1000
    else:
        return F(x - 1, F(x, y - 1))

print(str(F(x,y)))


#C++ Implementation

int f(int x,int y)
{
if(x==0)
    return (y+1)%1000;
if(x>0&&y==0)
    return f(x-1,1)%1000;
else
    return f(x-1,f(x,y-1));
}

int main()
{
 int x,y;
 scanf("%d%d",&x,&y);
 printf ("%03d", f(x,y));
 return 0;
}

Thanks in advance.

Prabhat Mishra
  • 951
  • 2
  • 12
  • 33
  • 1
    On an unrelated note, there is nothing in the "C++" code that is specific to C++, it could be a plain C program. On a more related note, the two programs are not *exactly* the same: The conditions in the functions are not the same (`elif` versus `else`). – Some programmer dude Nov 18 '18 at 06:10
  • updated pls check – Prabhat Mishra Nov 18 '18 at 06:13

2 Answers2

4
import resource, sys
resource.setrlimit(resource.RLIMIT_STACK, (2**29,-1))
sys.setrecursionlimit(10**6)

This would do. However try using memorisation to reduce recursive call if you can. If you really need the to do this via recursion then use above code and append it to the python code. It will increase the recursion limit of python which is I think 997.

Source : Setting stacksize in a python script

What is the maximum recursion depth in Python, and how to increase it?

Brij Raj Kishore
  • 1,595
  • 1
  • 11
  • 24
0

This is something like stack overflow prevention. Thats because python isnt particulary optimized for tail recursions.

You can change that limit, but it is not recommended (using sys.setrecursionlimit() ). If you are changing it default value set by interpreter is 1000.

FCulig
  • 1
  • 2