Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write recursive function that acts like sys.getrecursionlimit

How to write a recursive function that acts like sys.getrecursionlimit, thus getting the recursion limit without importing any libraries?

def recurse(n):
m = 0
def recurse2(n):
    nonlocal m 
    m = m+1
    n-recurse2(n-1)
try: 
    recurse2(n)
except RecursionError:
    print(m)

This is what I've attempted so far.

like image 620
roadrunner Avatar asked Apr 11 '26 14:04

roadrunner


2 Answers

Its easiest to pass a counter down to each function rather than try to access variables out of the function scope:

def get_limit():
    try:
        return 1 + get_limit()
    except RecursionError:
        return 2

which gives 1000 for me - just like sys.getrecursionlimit().


why?

So on every call of the function, the function adds one to the result of how many more recursive calls can be made. The answer to this question "how many [more] recursive calls can be made?" is simply answered by the function itself, so we return 1 + get_limit() since we were called so we must return one more.

Finally, we must define a base case which will lie at the bottom of the tree and handle when the answer to "how many [more] recursive calls can be made?" is RecursionError, i.e. "no more". In this case, the true answer is 1, but since the actual function will be called once, we should return 2 to account for the call at the top of the tree/stack so that our result is, in my case, 1000 rather than the 999 that it would be if we returned 1.

like image 164
Joe Iddon Avatar answered Apr 14 '26 03:04

Joe Iddon


You can use try/except inside the recursive function to be able to return the depth counter:

def _get_recursion_limit(n = 1):
  try:
     return _get_recursion_limit(n+1)
  except RecursionError:
     return n+1 #account for last attempt with increment

import sys
print(_get_recursion_limit())
print(sys.getrecursionlimit())

Output:

1000
1000

On my machine, both results are 1000.

like image 29
Ajax1234 Avatar answered Apr 14 '26 04:04

Ajax1234



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!