Source

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 my next post. ❤️ 👋

Newsletter

×

If you liked what you read then I am sure you will enjoy a newsletter of the content I create. I send it out every other month. It contains new stuff that I make, links I find interesting on the web, and occasional discount coupons for my book. Join the 5000+ other people who receive my newsletter:

I send out the newsletter once every other month. No spam, I promise + you can unsubscribe at anytime

✍️ Comments

phihag

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

   if x < 2: return x
   return fib(x-1) + fib(x-2)

you can write it iteratively like

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 )

Masimba Tutsie (@tutsie12)

not working babamunini

a v

Thank you for that. I had a perfectly working algorithm that required deeper stack to handle longer input. this worked - thanks again

Say something

Send me an email when someone comments on this post.

Thank you!

Your comment has been submitted and will be published once it has been approved. 😊

OK