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

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

  • автор:

Максимальная глубина рекурсии 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 не является функциональным языком, а рекурсия хвоста не является особенно эффективной техникой. Переписать алгоритм итеративно, если возможно, в целом, как правило, является лучшей идеей.

maximum recursion depth exceeded in comparison

I wrote this piece of code to compute the number of combinations:

The factorial function seems to work fine. But why does it give me a maximum recursion depth exceeded in comparison error when I try to find the combinations of two numbers? Is there something wrong with the factorial function, since that’s where the error seems to be originating from?

This was the error I got:

builtins.RuntimeError: maximum recursion depth exceeded in comparison

BartoszKP's user avatar

6 Answers 6

You should try to avoid recursion for such a simple function as the factorial of a number. Recursion is really powerful, but sometimes it is overused for no reason.

Here is the code for the iterative version of factorial function:

Notice what Maxime says in the previous answer, that is exactly the problem you are having: your function doesn’t contemplate the factorial of 0.

Because if you pass 2 identical numbers, you would try to compute fact(0) (which would call fact(-1) and fact(-2) , etc until the maximum recursion depth error).

The default recursion limit in python 3.x version onwards is 2000 only, If you call the same function again and again more than 2000 times, you will get maximum recursion depth error. The ideal approach would be to write a logic without recursion. But If you still stick to recursion, change the default recursion limit by:

sys.setrecursionlimit(10000)# It sets recursion limit to 10000.

But the above may not meet all your needs in certain contexts.

Your Recursion depth out of the limit.

Recursion is not the most idiomatic way to do things in Python, as it doesn’t have tail recursion optimization thus making impractical the use of recursion as a substitute for iteration (even if in your example the function is not tail-recursive, that wouldn’t help anyway). Basically, that means that you shouldn’t use it for things that have a complexity greater than linear if you expect your inputs to be large.

If you have a platform that supports a higher limit, you can set the limit higher:

This function set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care because a too-high limit can lead to a crash.

Python maximum recursion depth exceeded in comparison

Before jumping into an error, maximum recursion depth exceeded in comparison. Let’s first understand the basics of recursion and how recursion works in Python.

What is Recursion?

Recursion in computer language is a process in which a function calls itself directly or indirectly, and the corresponding function is called a recursive function.

A classic example of recursion

The most classic example of recursive programming everyone would have learned the factorial of a number. Factorial of a number is the product of all positive integers less than or equal to a given positive integer.

For example, factorial(5) is 5*4*3*2*1, and factorial(3) is 3*2*1.

Similarly, you can use recursive in many other scenarios like the Fibonacci series, Tower of Hanoi, Tree Traversals, DFS of Graph, etc.

Why does Python throw maximum recursion depth exceeded in comparison?

As we already know, recursive functions call by itself directly or indirectly, and during this process, the execution should go on infinitely.

Python limits the number of times a recursive function can call by itself to ensure it does not execute infinitely and cause a stack overflow error.

How to check maximum recursion depth in Python?

You can check the maximum recursion depth in Python using the code sys.getrecursionlimit(). Python doesn’t have excellent support for recursion because of its lack of TRE (Tail Recursion Elimination). By default, the recursion limit set in Python is 1000.

How do you fix the Recursionerror maximum recursion depth exceeded while calling a Python Object?

Let’s write a recursive function to calculate the Fibonacci series for a given number.

Since you are finding a Fibonacci of 1500 and the default recursion limit in Python is 1000, you will get an error stating “RecursionError: maximum recursion depth exceeded in comparison.”

This can be fixed by increasing the recursion limit in Python, below is the snippet on how you can increase the recursion limit.

Closing thoughts

This code sets the maximum recursion depth to 1500, and you could even change this to a higher limit. However, it is not recommended to perform this operation as the default limit is mostly good enough, and Python isn’t a functional language, and tail recursion is not a particularly efficient technique. Rewriting the algorithm iteratively, if possible, is generally a better idea.

Ezoic

report this ad

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 не будет опубликован. Обязательные поля помечены *