Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a stack overflow error in Python?

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.

like image 423
shamilpython Avatar asked May 29 '26 22:05

shamilpython


1 Answers

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.

like image 170
justwannalearn Avatar answered Jun 01 '26 10:06

justwannalearn