Maximum recursion depth exceeded in comparison python как исправить
Перейти к содержимому

Maximum recursion depth exceeded in comparison python как исправить

  • автор:

Python RecursionError: Maximum Recursion Depth Exceeded. Why?

You might have seen a Python recursion error when running your Python code. Why does this happen? Is there a way to fix this error?

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.

Let’s go through some examples so you can understand how this works.

The recursion begins!

RecursionError: Maximum Recursion Depth Exceeded in Comparison

Let’s create a program to calculate the factorial of a number following the formula below:

Write a function called factorial and then use print statements to print the value of the factorial for a few numbers.

This is a recursive function…

A recursive function is a function that calls itself. Recursion is not specific to Python, it’s a concept common to most programming languages.

You can see that in the else statement of the if else we call the factorial function passing n-1 as parameter.

The execution of the function continues until n is equal to 0.

Let’s see what happens when we calculate the factorial for two small numbers:

After checking that __name__ is equal to ‘__main__’ we print the factorial for two numbers.

But, here is what happens if we calculate the factorial of 1000…

The RecursionError occurs because the Python interpreter has exceeded the recursion limit allowed.

The reason why the Python interpreter limits the number of times recursion can be performed is to avoid infinite recursion and hence avoid a stack overflow.

Let’s have a look at how to find out what the recursion limit is in Python and how to update it.

What is the Recursion Limit in Python?

Open the Python shell and use the following code to see the value of the recursion limit for the Python interpreter:

Interesting…the limit is 1000.

To increase the recursion limit to 1500 we can add the following lines at the beginning of our program:

If you do that and try to calculate again the factorial of 1000 you get a long number back (no more errors).

…this solution could work if like in this case we are very near to the recursion limit and we are pretty confident that our program won’t end up using too much memory on our system.

How to Catch a Python Recursion Error

One possible option to handle the RecursionError exception is by using try except.

It allows to provide a clean message when your application is executed instead of showing an unclear and verbose exception.

Modify the “main” of your program as follows:

Note: before executing the program remember to comment the line we have added in the section before that increases the recursion limit for the Python interpreter.

Now, execute the code…

You will get the following when calculating the factorial for 1000.

Definitely a lot cleaner than the long exception traceback.

Interestingly, if we run our program with Python 2.7 the output is different:

We get back a NameError exception because the exception of type RecursionError is not defined.

RecursionError Python

Looking at the Python documentation I can see that the error is caused by the fact that the RecursionError exception was only introduced in Python 3.5:

So, if you are using a version of Python older than 3.5 replace the RecursionError with a RuntimeError.

In this way our Python application works fine with Python2:

How Do You Stop Infinite Recursion in Python?

As we have seen so far, the use of recursion in Python can lead to a recursion error.

How can you prevent infinite recursion from happening? Is that even something we have to worry about in Python?

Firstly, do you think the code we have written to calculate the factorial could cause an infinite recursion?

Let’s look at the function again…

This function cannot cause infinite recursion because the if branch doesn’t make a recursive call. This means that the execution of our function eventually stops.

We will create a very simple recursive function that doesn’t have an branch breaking the recursion…

When you run this program you get back “RecursionError: maximum recursion depth exceeded”.

So, in theory this program could have caused infinite recursion, in practice this didn’t happen because the recursion depth limit set by the Python interpreter prevents infinite recursion from occurring.

How to Convert a Python Recursion to an Iterative Approach

Using recursion is not the only option possible. An alternative to solve the RecursionError is to use a Python while loop.

We are basically going from recursion to iteration.

  • Multiply the latest value of the factorial by n
  • Decrease n by 1

The execution of the while loop continues as long as n is greater than 0.

I want to make sure that this implementation of the factorial returns the same results as the implementation that uses recursion.

So, let’s define a Python list that contains a few numbers. Then we will calculate the factorial of each number using both functions and compare the results.

We use a Python for loop to go through each number in the list.

Our program ends as soon as the factorials calculated by the two functions for a given number don’t match.

Let’s run our program and see what we get:

Our implementation of the factorial using an iterative approach works well.


In this tutorial we have seen why the RecursionError occurs in Python and how you can fix it.

[Solved] RecursionError: maximum recursion depth exceeded while calling a Python object

RecursionError maximum recursion depth exceeded while calling a Python object

A Recursive function in programming is a function which calls itself. These functions find applications while constructing programs for factorial, Fibonacci series , Armstrong numbers, etc. The main idea is to break larger programs into smaller, less complex problems. With recursive functions, generating sequences becomes easy. But while using recursive functions, recursionerror may occur in python. In this article, we shall be looking into one such recursionerror: maximum recursion depth exceeded while calling a Python object

What is recursionerror?

As the name suggests, Recursionerror may occur when we are dealing with recursive functions. When we run the recursion function for a large number of times, recursion error is thrown. Python has a limit on the number of times a recursive function can call itself. This is done to ensure that the function does not execute infinitely and stops after some number of iterations. To know the recursion limit in python, we use the following code:

The output is:

RecursionError: Maximum Recursion Depth Exceeded while calling a Python Object

Let us look at an example of RecursionError: maximum recursion depth exceeded. We shall take an example of a factorial function .

The following code shall generate factorial for a given number.

Here, this program shall be executed successfully and shall print the below output:

But if we pass a larger number into the find_fact() function, it will throw RecursionError: Maximum Recursion Depth Exceeded error.


Since the recursion function exceeded the limit of 1000 iterations, recursionerror is thrown.

The RecursionError: Maximum Recursion Depth Exceeded error may also be thrown while we are trying to create a nested list whose length exceeds the recursion limit.

Let us take the following example. We have created a function named nested() which accepts one argument – n. Depending on the value of n, the length of that nested list would be created. Let us try to pass a value n greater than the recursion limit.

The output will be a recursion error.

RecursionError: Maximum Recursion Depth Exceeded While Calling A Python Object

The recursionerror for Maximum Recursion Depth Exceeded While Calling A Python Object is thrown when we are trying to call a python object in Django. The error may also occur while using Flask.

When the interpreter detects that the maximum depth for recursion has reached, it throws the recursionerror. To prevent the stack from getting overflow, python raises the recursionerror.

Best practices to avoid RecursionError: Maximum Recursion Depth Exceeded while calling a Python Object

1. Using other loops instead of recursion

To prevent the error from occurring, we can simply convert the piece of code from recursion to a loop statement.

If we take the example of the factorial function, we can convert it into a non – recursive function. We do that by placing a for loop inside the recursion function. The for loop will execute for a length equal to the value of the factorial number.

Now, it will not throw any recursion error and simply print the large factorial number.

2. Using sys.setrecursionlimit() function

Else, if we still want to use the recursion function, we can increase the recursion limit from 1000 to a higher number. For that, we have to first import the sys library. Using the sys library, we will use the sys.setrecursionlimit() function.

Now, it will not thrown the recursionerror and the program will be executed for larger amount of recursions. On executing the recursive function, it will not throw any error and print its output.

3. Setting boundary conditions

It is necessary to set boundary conditions to ensures that the recursive function comes to an end. In the factorial program, the condition :

is the boundary condition. It is with this condition that the loop comes to an end.

4. Creating a converging recursion

While writing the recursion condition, one has to ensure that the condition does come to an end and does not continue infinitely. The recursive calls should eventually tend towards the boundary condition.

We have to ensure that we creating a converging condition for that. In the factorial program, the ‘n*fact(n-1)’ is a converging condition that converges the value from n to 1.

5. Using Memoization

We can also use memoization to reduce the computing time of already calculated values. This way, we can speed up the calculations by remembering past calculations.

When recursive calls are made, then with memoization we can store the previously calculated values instead of unnecessarily calculating them again.

That sums up the article on RecursionError: Maximum Recursion Depth Exceeded While Calling A Python Object. If you have any questions in your mind, don’t forget to let us know in the comments below.

Максимальная глубина рекурсии Python превышена в сравнении

Ismycode |. Прежде чем прыгать в ошибку, превышена максимальная глубина рекурсии по сравнению. Давайте … Помечено с Python, программированием, CodeNewie.

  • Автор записи

Прежде чем прыгать в ошибку, Максимальная глубина рекурсии превышена в сравнении Отказ Сначала понять основы рекурсии и как работает рекурсион в Python.

Что такое рекурсия?

Рекурсия на языке компьютерных языков – это процесс, в котором функция вызывает себя прямо или косвенно, и соответствующая функция называется рекурсивной функцией.

Классический пример рекурсии

Наиболее классическим примером рекурсивного программирования каждый извлек факториал номера. Факториал числа – это Продукт всех положительных целых чисел меньше или равен данному положительному целым числу.

Например, факториал (5) составляет 5 * 4 * 3 * 2 * 1, а факториал (3) составляет 3 * 2 * 1.

Точно так же вы можете использовать рекурсивные во многих других сценариях, таких как Фибоначчи серии , Башня Ханой , Обход деревьев , DFS графа , и т.д.

Почему Python бросает максимальную глубину рекурсии в сравнении?

Как мы уже знаем, рекурсивные функции вызывают сама прямо или косвенно, и во время этого процесса выполнение должно пройти бесконечно.

Python ограничивает количество раз, когда рекурсивная функция может позвонить сам по себе, чтобы убедиться, что она не выполняется бесконечно и вызывает ошибку переполнения стека.

Как проверить максимальную глубину рекурсии в Python?

Вы можете проверить максимальную глубину рекурсии в Python, используя код Sys.getRecursionLimit (). Python не имеет отличной поддержки для рекурсии из-за отсутствия TRE (устранение рекурсионного хвоста). По умолчанию предельный предел рекурсии в Python составляет 1000.

Как вы исправите максимальную глубину рекурсии RecursionError, при вызове объекта Python?

Давайте напишем рекурсивную функцию для расчета серии Fibonacci для данного номера.

Поскольку вы найдете фибоначчи из 1500, а лимит рекурсии по умолчанию в Python является 1000, вы получите ошибку « RecursionError: максимальная глубина рекурсии превышена в сравнении ».

Это может быть исправлено, увеличивая предел рекурсиона в Python, ниже – фрагмент о том, как вы можете увеличить предел рекурсии.

Закрытие мыслей

Этот код устанавливает максимальную глубину рекурсии до 1500, и вы даже можете изменить это на более высокий предел. Тем не менее, не рекомендуется выполнять эту операцию, так как ограничение по умолчанию в основном достаточно хорош, и Python не является функциональным языком, а рекурсия хвоста не является особенно эффективной техникой. Переписать алгоритм итеративно, если возможно, в целом, как правило, является лучшей идеей.

What Is the Maximum Recursion Depth in Python

The maximum recursion depth in Python is 1000.

You can verify this by calling sys.getrecursionlimit() function:

You can change the limit by calling sys.setrecursionlimit() method.

Consider this a dangerous action!

If possible, instead of tweaking the recursion limit, try to implement your algorithm iteratively to avoid deep recursion.

Python Maximum Recursion Depth Exceded in Comparison

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. This tells you that Python’s recursion depth limit of 1000 is reached.

But why is there such a limit? More importantly, how can you overcome it?

Let’s answer these questions next.

Why Is There a Recursion Depth Limit in Python

A recursive function could call itself indefinitely. In other words, you could end up with an endless loop.

Also, a stack overflow error can occur even if the recursion is not infinite. This can happen due to too big of a stack frame.

In Python, the recursion depth limit takes these risks out of the equation.

Python uses a maximum recursion depth of 1000 to ensure no stack overflow errors and infinite recursions are possible.

This recursion limit is somewhat conservative, but it is reasonable as stack frames can become big in Python.

What Is a Stack Overflow Error in Python

Stack overflow error is usually caused by too deep (or infinite) recursion.

This means a function calls itself so many times that the space needed to store the information related to each call is more than what fits on the stack.

How to Change the Recursion Depth Limit in Python—Danger Zone!

You can change the maximum recursion depth in Python. But consider it a dangerous action.

To do this, call the sys.setrecursionlimit() function.

For example, let’s set the maximum recursion depth to 2000 :

Temporarily Change the Recursion Depth Limit in Python

Do you often need to tweak the recursion depth limit in your project?

If you do, consider using a context manager. This can improve the quality of your code.

For example, let’s implement a context manager that temporarily switches the recursion limit:

Now you can temporarily change the recursion depth to perform a recursive task.

When this operation completes, the context manager automatically switches the recursion depth limit back to the original value.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *