python

Fixing error – maximum recursion depth reached

Hi there folks. In this post I am going to teach you how to increase the recursion depth in python. Most of us at some time get this error :

RuntimeError: maximum recursion depth exceeded

If you want to fix this error just increase the default recursion depth limit but how to do it ? Just import the sys module in your script and in the beginning of the script type this :

sys.setrecursionlimit(1500)

This will increase the default limit to 1500. For the record the default limit is 1000. I hope that you found this post useful. Do share this on facebook and twitter and stay tuned for our next post.

Advertisements
Standard

2 thoughts on “Fixing error – maximum recursion depth reached

  1. phihag says:

    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)

    you can write it iteratively like

    import collections
    def fib(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

    As you can see, the iterative variant is quite messy, but it makes the state explicit. (Full code at http://ideone.com/oqS0pY )

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s