0
import sys

def Factorial(i):
    if i == 1:
        return 1
    else:
        return i*Factorial(i-1)
    
sys.getrecursionlimit()

factorials = []
OOB = []

for i in range(1,3001):
    try:
        factorials.append(Factorial(i))
    except RecursionError:
        OOB.append(i)

print(OOB)

sys.getrecursionlimit() returns the max recursion depth as 3000. However, the function Factorial() returns a RecursionError for all i>2984 [The list 'OOB' contained all 2985 ≤ i ≤ 3000] As per the default system recursion depth, shouldn't the limit be till i = 2998 or i = 2999 ? Why is there a discrepancy here? If this question indicates a flaw in my understanding of recursion depth, please explain/guide to resources.

  • also by changing the recursion limit the new threshold value is not really respected. Don't know why – cards Mar 15 '22 at 18:27
  • 3
    Cannot reproduce. On my system, the limit is 1000 and this loop fails on i=999. – John Gordon Mar 15 '22 at 18:29
  • 1
    So, recursion limit is a bit misleading. It's really a stack limit. Recursive or otherwise. How exactly are you running this code? If, for example, you are using some tool as a part of our IDE, there may be a bigger stack to begin with – juanpa.arrivillaga Mar 15 '22 at 18:40
  • 1
    So, for eample, you have `sys.getrecursionlimit()` just sitting there, doing nothing. Are you running this in an IPython REPL by any chance? Or a Jupyter notebook? – juanpa.arrivillaga Mar 15 '22 at 20:39
  • Apparently I have a similar system as @JohnGordon, plus I also tried calling `setrecursionlimit()`, which works until somewhere above 2400 (where I get a list of numbers starting with 2399), but below 2500 (where my Python 3.9.1 on 64-bit Windows simply dies and the list doesn't get printed). – tevemadar Mar 16 '22 at 00:18
  • Don't use recursion for linear stack depth algorithms and you'll (basically) never have any problem with this. See [this answer](https://stackoverflow.com/a/66846438/6243352) for elaboration. Stack depth is a system-dependent factor that you shouldn't count on being set to a certain limit. – ggorlen Mar 16 '22 at 17:11
  • @cards It is respected when I run it on my system. Eg: setrecursionlimit(5000) allows the function to run up to i = 4984. The discrepancy is consistent though. – Jeril Philip Apr 02 '22 at 14:01
  • @JohnGordon thank you for indicating that it is a system specific limit. – Jeril Philip Apr 02 '22 at 14:02
  • @ggloren thanks for the link. Still don't fully understand how exactly the depth is calculated but I'm sure I'll find an explanation if I look in that direction. – Jeril Philip Apr 02 '22 at 14:02
  • @Jeril Philip have you tried with 50 or 80? – cards Apr 02 '22 at 14:18

0 Answers0