#That's a band-aid though. Instead of going into these crazy-deep (at least for Python, it would be another story in LISP or Haskell) recursions, you should rewrite your algorithm to an iterative one. If it is tail-recursive, a loop will suffice. In other cases, you can simply keep a list of tasks. For example, instead of
def fib( x) :
if x < 2 : return x
return fib( x-1 ) + fib( x-2 )
#write
import collections
def fib_iter( x) :
tasks = collections .deque ( [ x] )
res = 0
while tasks:
v = tasks.pop ( )
if v < 2 :
res += v
continue
tasks.append ( v-1 )
tasks.append ( v-2 )
return res
for i in range ( 10 ) :
assert fib_iter( i) == fib( i) , 'Got %r, expected %r for fib(%d)' % ( fib_iter( i) , fib( i) , i)
I1RoYXQncyBhIGJhbmQtYWlkIHRob3VnaC4gSW5zdGVhZCBvZiBnb2luZyBpbnRvIHRoZXNlIGNyYXp5LWRlZXAgKGF0IGxlYXN0IGZvciBQeXRob24sIGl0IHdvdWxkIGJlIGFub3RoZXIgc3RvcnkgaW4gTElTUCBvciBIYXNrZWxsKSByZWN1cnNpb25zLCB5b3Ugc2hvdWxkIHJld3JpdGUgeW91ciBhbGdvcml0aG0gdG8gYW4gaXRlcmF0aXZlIG9uZS4gSWYgaXQgaXMgdGFpbC1yZWN1cnNpdmUsIGEgbG9vcCB3aWxsIHN1ZmZpY2UuIEluIG90aGVyIGNhc2VzLCB5b3UgY2FuIHNpbXBseSBrZWVwIGEgbGlzdCBvZiB0YXNrcy4gRm9yIGV4YW1wbGUsIGluc3RlYWQgb2YKCmRlZiBmaWIoeCk6CiAgIGlmIHggPCAyOiByZXR1cm4geAogICByZXR1cm4gZmliKHgtMSkgKyBmaWIoeC0yKQoKI3dyaXRlCgppbXBvcnQgY29sbGVjdGlvbnMKZGVmIGZpYl9pdGVyKHgpOgogICAgdGFza3MgPSBjb2xsZWN0aW9ucy5kZXF1ZShbeF0pCiAgICByZXMgPSAwCiAgICB3aGlsZSB0YXNrczoKICAgICAgICB2ID0gdGFza3MucG9wKCkKICAgICAgICBpZiB2IDwgMjoKICAgICAgICAgICAgcmVzICs9IHYKICAgICAgICAgICAgY29udGludWUKICAgICAgICB0YXNrcy5hcHBlbmQodi0xKQogICAgICAgIHRhc2tzLmFwcGVuZCh2LTIpCiAgICByZXR1cm4gcmVzCgpmb3IgaSBpbiByYW5nZSgxMCk6CiAgICBhc3NlcnQgZmliX2l0ZXIoaSkgPT0gZmliKGkpLCAnR290ICVyLCBleHBlY3RlZCAlciBmb3IgZmliKCVkKScgJSAoZmliX2l0ZXIoaSksIGZpYihpKSwgaSk=