9

I currently use this code:

def f():
    try:
        f()
    except RecursionError:
        f()

try:
    f()
except RecursionError:
    f()

This results in a fatal stack overflow instantly. However, I was wondering if there is an easier way to do this which is much more Pythonic.

8
  • This seems pretty pythonic to me Commented Jul 27, 2018 at 4:07
  • 1
    You might remove the outer try block, just leave the one in the function. Commented Jul 27, 2018 at 4:08
  • Just out of curiosity, what prompted this question? Commented Jul 27, 2018 at 4:09
  • 3
    I don't think crashing the Python interpreter is a very Pythonic thing to do in the first place. Commented Jul 27, 2018 at 4:15
  • Also, I'm pretty sure this is CPython-specific. If you try it in PyPy, you'll probably eventually get a MemoryError (but only after waiting for your system to go through swap hell for a while, at least in 64-bit), and in Jython you should get a (catchable) Java StackOverflowError rather than a fatal crash. Commented Jul 27, 2018 at 4:17

2 Answers 2

3
import sys
sys.setrecursionlimit(10**8)

def ackermann(m,n):
     if m == 0:
          return (n + 1)
     elif n == 0:
          return ackermann(m - 1, 1)
     else:
          return ackermann(m - 1, ackermann(m, n - 1)) 
          
for x in range(5):
    for y in range(5):
        print(ackermann(x, y)) 

Python's default recursion limit is 10**4. Changable with setrecursionlimit() so you can get a 'Stack overflow' error because Ackermann function's output is too long.

Sign up to request clarification or add additional context in comments.

1 Comment

Seems over complicated
0

I like to use

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

to test max recursion. It will throw a 'RecursionError: maximum recursion depth exceeded in comparison' if n is to large.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.