Home > Mobile >  Can I set recursion depth more than 10^12 in python3?
Can I set recursion depth more than 10^12 in python3?

Time:02-19

I'm trying to use a recursive function with almost 10^12 of recursion depth. I used setrecursionlimit(10 ** 12) , but error occurred with error message; OverflowError: Python int too large to convert to C int

Should I change the solution that can solved in lower recursion depth? Or, is there any way that can set the recursion depth as 10^12 in python3?

CodePudding user response:

The short answer is No. The value is too large the parameter type of the function that sets the depth limit.

The long answer is "You shouldn't have to" because that depth level is a clear indicator that recursion isn't the best approach. Any recursive function can be converted to an equivalent (and usually faster / more efficient) iterative alternative. You may want to look into the deque module to help with the conversions of the stack management.

CodePudding user response:

The max recursion limit is platform dependent. You're limited in range to a signed C integer.

On my system that's a 4 byte (32-bit) signed int.

>>> import ctypes
>>> print(ctypes.sizeof(ctypes.c_int))
4
>>> sys.setrecursionlimit(2**31)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C int

>>> sys.setrecursionlimit(2**31-1)  # no exception

As explained in other answers/comments, I would never attempt to approach that limit in practice. Every recursive solution can be converted to iteration.

  • Related