Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a recursive program run for a long time without getting RunTimeError in Python

This code is the recursive factorial function.

The problem is that if I want to calculate a very large number, it generates this error: RuntimeError : maximum recursion depth exceeded

import time

def factorial (n) :        
    if n == 0:
        return 1
    else:            
        return n * (factorial (n -1 ) )

print " The factorial of the number is: " , factorial (1500)

time.sleep (3600)

The goal is to do with the recursive function is a factor which can calculate maximum one hour.

like image 775
Camilo B. Mariño Avatar asked May 19 '26 04:05

Camilo B. Mariño


1 Answers

This is a really bad idea. Python is not at all well-suited for recursing that many times. I'd strongly recommend you switch this to a loop which checks a timer and stops when it reaches the limit.

But, if you're seriously interested in increasing the recursion limit in cython (the default depth is 1000), there's a sys setting for that, sys.setrecursionlimit. Note as it says in the documentation that "the highest possible limit is platform-dependent" - meaning there's no way to know when your program will fail. Nor is there any way you, I or cython could ever tell whether your program will recurse for something as irrelevant to the actual execution of your code as "an hour." (Just for fun, I tried this with a method that passes an int counting how many times its already recursed, and I got to 9755 before IDLE totally restarted itself.)

Here's an example of a way I think you should do this:

# be sure to import time
start_time = time.time()
counter = 1

# will execute for an hour
while time.time() < start_time + 3600:
    factorial(counter) # presumably you'd want to do something with the return value here
    counter += 1

You should also keep in mind that regardless of whether you use iteration or recursion, (unless you're using a separate thread) you're still going to be blocking the entire program for the entirety of the hour.

like image 70
furkle Avatar answered May 20 '26 17:05

furkle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!