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.

2
  • 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). Commented Nov 18, 2018 at 6:10
  • updated pls check Commented Nov 18, 2018 at 6:13

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.