Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to set the recursion limit to infinite in Python? [duplicate]

So I was trying to make a simple program that would calculate the sum of the harmonic series and then print the results. But then the recursion limit stops it from going on.

Here is the program:

def harm_sum(n):
    if n < 2:
        return 1
    else: 
return (1 / n) + (harm_sum(n - 1))

x = 1
while True:
    print(x, harm_sum(x))
    x += 1

I want the program to keep on running despite the recursion limit is there a way to do that?

like image 479
jakacop Avatar asked Mar 07 '23 18:03

jakacop


1 Answers

Direct answer: No, you cannot disable the stack limit; it's there to avoid using up all the available stack space, which would crash your run without any Traceback information.

Also, note that it's not possible to have an infinite stack size: each stack frame occupies RAM; you'll eventually run out and crash the system.

Workaround: If you can handle a hard crash, then simply use sys.setrecursionlimit to set it beyond the physical limits of your system (which are system-dependent).

Real solution: as Juan already noted, you can simply re-code your recursion as a loop.

like image 185
Prune Avatar answered May 12 '23 15:05

Prune