How do you fix RecursionError maximum recursion depth exceeded in comparison?

Dung Do Tien Aug 15 2021 323

Hello Everyone, I have a small project with Python 3.8.2 and I have created a method to help find numbers with recursive as below:

def find_number(n):   if n == 0 or n == 1:     return 1   else :     return (n * find_number(n-1))     print("Factorial is :", find_number(10))

It works very well for me and returns 3628800. But when I set the param value to 1000 I got the error RecursionError: maximum recursion depth exceeded in comparison

print("Factorial is :", find_number(1000))

Traceback (most recent call last):   File "main.py", line 7, in <module>     print("Factorial is :", find_number(1000))   File "main.py", line 5, in find_number     return (n * find_number(n-1))     File "main.py", line 5, in find_number     return (n * find_number(n-1))     File "main.py", line 5, in find_number     return (n * find_number(n-1))     [Previous line repeated 995 more times]   File "main.py", line 2, in find_number     if n == 0 or n == 1: RecursionError: maximum recursion depth exceeded in comparison

I still do not understand why it occurs. How can I fix it?

Have 2 answer(s) found.

  • You can use sys.setrecursionlimit() function to help increase the max number for recursive:

    import sys sys.setrecursionlimit(2000)

  • Jair Rojas Garcia Aug 15 2021

    I think the best practice to avoid this error is to use other loops instead of recursion. Like:

    def find_number(n):   num = 1   for i in range(2, n + 1):     num = num * i   return num   print("Factorial is :", find_number(1000))

    It works very well for me.

If this answer is useful for you, please BUY ME A COFFEE!!! I need your help to maintain blog.

  1. ImportError: cannot import name 'get_config' from 'tensorflow.python.eager.context'
  2. Error: pg_config executable not found in Python 3.10
  3. ValueError: Can only compare identically-labeled DataFrame objects in Python
  4. ValueError: I/O operation on closed file in Python 3
  5. AttributeError: 'dict' object has no attribute 'has_key' in Python
  6. AttributeError: type object 'datetime.datetime' has no attribute 'timedelta' in Python
  7. AttributeError: 'DataFrame' object has no attribute 'as_matrix' in Python
  8. AttributeError: 'DataFrame' object has no attribute 'price' in Python
  9. SyntaxError: non-default argument follows default argument in Python
  10. Error: BrokenPipeError: [Errno 32] Broken pipe in Python 3
  11. Throw ImportError: No module named boto3 in Python 3
  12. AttributeError: 'str' object has no attribute 'decode' in Python
  13. TypeError: 'dict_values' object is not subscriptable in Python
  14. AttributeError: module 'datetime' has no attribute 'strptime' in Python
  15. How can I check If a file exists or not in Python 3?

Leave An Answer

* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.


In this article, you will learn about how to fix RecursionError: maximum recursion depth exceeded in comparison in python.

The RecursionError: maximum recursion depth exceeded in comparison in python is occurred because of exceeding the recursion limit. The maximum recursion depth in python is 1000 and if you cross this limit then you will face this error. Recursion is very useful and may solve many complex problems easily but if you don’t know how to use it then it can cause many serious issues like this error. In this article, we are going to see the solution to this error. Before doing so, let’s check the recursion depth in python in the below code example:

import sys print(sys.getrecursionlimit()) # Output: 1000

Here, you can see that the limit of the recursion depth in python is 1000 and if we cross this limit then that error will occur. Let’s say we want to print the Fibonacci series of 1200. Let me assume that, you already know the concept of the Fibonacci series. Let’s implement it in the below section:

def fibonacci_seris(num): if num <= 1: return num else: return(fibonacci_seris(num-1) + fibonacci_seris(num-2)) print(fibonacci_seris(1200))

Here, you can see that we are trying to calculate the 1200 Fibonacci number using recursion but we have already known about the recursion depth in python and that is 1000. So we may assume that we will get an error if we run our program. Let’s do it and see what happens in the below section:

How do you fix RecursionError maximum recursion depth exceeded in comparison?

You can see that we are getting that error as we have expected. The solution for this issue is to increase the Recursion depth. To do so, follow the below code example:

import sys sys.setrecursionlimit(1500) print(sys.getrecursionlimit()) # Output: 1500

Here, you can see that we have increased the recursion depth from 1000 to 1500 manually in python. Now if you run your program again then you will see that the error has been gone and you are getting your output as expected. You may increase the limit as much as you want. But it is not recommended to use recursion depth in this way. if the recursion depth crosses its limit then you should avoid it and find out other reliable solutions. But if you have faced this issue then by following this approach you may fix this problem.

Share on social media

//

PreviousNext

How can you prevent maximum recursion depth exceeded?

Try increasing the recursion limit ( sys. setrecursionlimit ) or re-writing your code without recursion. Return the current value of the recursion limit, the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.

How do I fix RecursionError in Python?

A Python RecursionError exception is raised when the execution of your program exceeds the recursion limit of the Python interpreter. Two ways to address this exception are increasing the Python recursion limit or refactoring your code using iteration instead of recursion.

What does RecursionError maximum recursion depth exceeded?

Whenever you exceed the recursion depth of 1000, you get an error in Python. For example, if we try to compute a too large Fibonacci number, we get the recursion depth error. This error says it all—maximum recursion depth exceeded in comparison.

What causes recursion error?

In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). When there are too many function calls, or a function is missing a base case, JavaScript will throw this error.