Recursionerror maximum recursion depth exceeded in comparison ошибка

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

def fact(n):
    return 1 if(n == 1) else n * fact(n - 1)

def combinations(n,k):
    return fact(n)/((fact(n - k) * fact(k)))

while(True):
    print(combinations(int(input()), int(input())))

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

BartoszKP

34.5k14 gold badges101 silver badges129 bronze badges

asked Nov 17, 2013 at 17:47

Daniel Cook's user avatar

2

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:

def fact(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

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.

answered Nov 17, 2013 at 18:40

educampver's user avatar

educampvereducampver

2,9572 gold badges23 silver badges34 bronze badges

Try to replace:

def fact(n):
    return 1 if(n == 1) else n * fact(n - 1)

to:

def fact(n):
    return 1 if(n <= 1) else n * fact(n - 1)

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).

answered Nov 17, 2013 at 17:51

Maxime Chéramy's user avatar

Maxime ChéramyMaxime Chéramy

17.6k8 gold badges54 silver badges74 bronze badges

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:

import sys

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

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

answered Sep 27, 2017 at 14:31

Siva Kumar's user avatar

Siva KumarSiva Kumar

4394 silver badges6 bronze badges

1

Your Recursion depth out of the limit.

  1. 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.

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

    sys.setrecursionlimit(some_number)
    sys.setrecursionlimit(some_number)

    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.

ref:
Python recursive function error: “maximum recursion depth exceeded”
Python max recursion , question about sys.setrecursionlimit()

answered Jul 18, 2017 at 7:41

hxysayhi's user avatar

hxysayhihxysayhi

1,85818 silver badges24 bronze badges

sys.setrecursionlimit(some_number)

Floern's user avatar

Floern

33.4k24 gold badges104 silver badges119 bronze badges

answered Jul 13, 2017 at 11:07

user8301642's user avatar

something like this works well:

def factorial_by_recursion(max_number, current_number, somme):
    if current_number < max_number:
        somme += current_number
        return factorial_by_recursion(max_number, current_number + 1, somme)
    else:
        return somme

answered Oct 13, 2019 at 19:00

Yann Kull's user avatar

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!

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

n! = n * (n-1) * (n-2) * ... * 1

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

def factorial(n):
    if n == 0:
        return 1
    else:
        return n*factorial(n-1) 

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:

if __name__ == '__main__': 
    print("The factorial of 4 is: {}".format(factorial(4)))
    print("The factorial of 5 is: {}".format(factorial(5)))

[output]
The factorial of 4 is: 24
The factorial of 5 is: 120 

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

It’s all good.

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

print("The factorial of 1000 is: {}".format(factorial(1000)))

[output]
Traceback (most recent call last):
  File "recursion_error.py", line 9, in <module>
    print("The factorial of 1000 is: {}".format(factorial(1000)))
  File "recursion_error.py", line 5, in factorial
    return n*factorial(n-1)
  File "recursion_error.py", line 5, in factorial
    return n*factorial(n-1)
  File "recursion_error.py", line 5, in factorial
    return n*factorial(n-1)
  [Previous line repeated 995 more times]
  File "recursion_error.py", line 2, in factorial
    if n <= 1:
RecursionError: maximum recursion depth exceeded in comparison 

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:

>>> import sys
>>> print(sys.getrecursionlimit())
1000 

Interesting…the limit is 1000.

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

import sys
sys.setrecursionlimit(1500)

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

The factorial of 1000 is: 4023872600770937735437024339230039857193748642107146325437999104299385123986290205920
.......835777939410970027753472000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

That’s good! But…

…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:

if __name__ == '__main__':
    try:
        print("The factorial of 1000 is: {}".format(factorial(1000)))
    except RecursionError as re:
        print("Unable to calculate factorial. Number is too big.") 

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.

$ python recursion_error.py
Unable to calculate factorial. Number is too big. 

Definitely a lot cleaner than the long exception traceback.

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

$ python2 recursion_error.py 
Traceback (most recent call last):
  File "recursion_error.py", line 13, in <module>
    except RecursionError as re:
NameError: name 'RecursionError' is not defined 

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

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:

RecursionError Python

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

if __name__ == '__main__':
    try:
        print("The factorial of 1000 is: {}".format(factorial(1000)))
    except RuntimeError as re:
        print("Unable to calculate factorial. Number is too big.") 

In this way our Python application works fine with Python2:

$ python2 recursion_error.py
Unable to calculate factorial. Number is too big. 

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…

def factorial(n):
    if n == 0:
        return 1
    else:
        return n*factorial(n-1) 

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…

def recursive_func():
    recursive_func()

recursive_func() 

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

$ python recursion_error2.py
Traceback (most recent call last):
  File "recursion_error2.py", line 4, in <module>
    recursive_func()
  File "recursion_error2.py", line 2, in recursive_func
    recursive_func()
  File "recursion_error2.py", line 2, in recursive_func
    recursive_func()
  File "recursion_error2.py", line 2, in recursive_func
    recursive_func()
  [Previous line repeated 996 more times]
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.

def factorial(n):
    factorial = 1

    while n > 0:
        factorial = factorial*n
        n = n - 1

    return factorial

Firstly we set the value of the factorial to 1 and then at each iteration of the while loop we:

  • 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.

def factorial(n):
    factorial = 1

    while n > 0:
        factorial = factorial*n
        n = n - 1

    return factorial

def recursive_factorial(n):
    if n == 0:
        return 1
    else:
        return n*factorial(n-1)

numbers = [4, 9, 18, 23, 34, 56, 78, 88, 91, 1000] 

for number in numbers:
    if factorial(number) != recursive_factorial(number):
        print("ERROR: The factorials calculated by the two functions for the number {} do not match.".format(number))

print("SUCCESS: The factorials calculated by the two functions match") 

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

$ python factorial.py
SUCCESS: The factorials calculated by the two functions match 

Great!

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

Conclusion

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

Two options you have are:

  • Increase the value of the recursion limit for the Python interpreter.
  • Use iteration instead of recursion.

Which one are you going to use?

Claudio Sabato - Codefather - Software Engineer and Programming Coach

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

Ismycode |.

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

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

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

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

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

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

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

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

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

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

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

def fibonacci(n):
    if n <= 1:
        return n
    else:
        return(fibonacci(n-1) + fibonacci(n-2))
print(fibonacci(1500))

#Output RecursionError: maximum recursion depth exceeded in comparison

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

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

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

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

import sys
sys.setrecursionlimit(1500)

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

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

Пост Максимальная глубина рекурсии Python превышена в сравнении появился первым на INSMYCODE Отказ

Оригинал: “https://dev.to/itsmycode/python-maximum-recursion-depth-exceeded-in-comparison-4a70”

The maximum recursion depth in Python is 1000.

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

import sys

print(sys.getrecursionlimit()) # Prints 1000

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

For example:

import sys

print(sys.setrecursionlimit(2000))

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.

# A function for computing Fibonacci numbers
def fibonacci(n):
   if n <= 1:
       return n
   else:
       return(fibonacci(n-1) + fibonacci(n-2))

# Let's call the 1000th Fibonacci number:
print(fibonacci(1000))

Output:

  File "example.py", line 2, in fibonacci
    if n <= 1:
RecursionError: maximum recursion depth exceeded in comparison

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:

import sys

print(sys.setrecursionlimit(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:

import sys

class recursion_depth:
    def __init__(self, limit):
        self.limit = limit
        self.default_limit = sys.getrecursionlimit()

    def __enter__(self):
        sys.setrecursionlimit(self.limit)

    def __exit__(self, type, value, traceback):
        sys.setrecursionlimit(self.default_limit)

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

For instance:

with recursion_depth(2000):
    print(fibonacci(1000, 0))

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

Learn more about the with statement and context managers in Python here.

Conclusion

The recursion depth limit in Python is by default 1000. You can change it using sys.setrecursionlimit() function.

Thanks for reading. I hope you enjoy it.

Happy coding!

Further Reading

Python Interview Questions and Answers

Useful Advanced Features of Python

Resources

StackOverflow

About the Author

I’m an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.

Recent Posts

Table of Contents
Hide
  1. What is Recursion?
  2. A classic example of recursion
  3. Why does Python throw maximum recursion depth exceeded in comparison?
  4. How to check maximum recursion depth in Python?
  5. How do you fix the Recursionerror maximum recursion depth exceeded while calling a Python Object?
  6. Closing thoughts

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 seriesTower of HanoiTree TraversalsDFS of Graph, etc.

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.

def fibonacci(n):
	if n <= 1:
		return n
	else:
		return(fibonacci(n-1) + fibonacci(n-2))
print(fibonacci(1500))

#Output RecursionError: maximum recursion depth exceeded in comparison

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.

import sys
sys.setrecursionlimit(1500)

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.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Понравилась статья? Поделить с друзьями:
  • Reaction электросамокат ошибка e5
  • React обработчик ошибок
  • React обработка ошибок от api
  • React axios обработка ошибок
  • Reached end of file while parsing java ошибка