Recursionerror: maximum recursion depth exceeded while calling a python object

붕어사랑 티스토리

  • 관리
  • 글쓰기
  • 로그인
  • 로그아웃

  • 태그
  • 방명록

Python/알고리즘팁

by 붕어사랑 티스토리 2021. 3. 11.

반응형

파이썬에서는 기본적으로 재귀함수 호출을 1000으로 제한하고있다.

아래의 방법으로 recursion limit 제한을 커스텀 할 수 있다.

import sys sys.setrecursionlimit(9999)

반응형

저작자표시

'Python > 알고리즘팁' 카테고리의 다른 글

파이썬 Counter 객체 사용하기  (0) 2021.03.12
list indices must be integers or slices, not float  (0) 2021.03.11
파이썬 print 줄바꿈 없이 출력하기  (0) 2021.03.11
RecursionError: maximum recursion depth exceeded while calling a Python object  (0) 2021.03.11
파이썬 heapq 커스텀 정렬 이용하기  (3) 2021.03.10
파이썬 커스텀 정렬 이용하기  (0) 2021.03.10

태그

재귀함수, 파이썬

관련글

  • list indices must be integers or slices, not float
  • 파이썬 print 줄바꿈 없이 출력하기
  • 파이썬 heapq 커스텀 정렬 이용하기
  • Recursionerror: maximum recursion depth exceeded while calling a python object
    파이썬 커스텀 정렬 이용하기

댓글0

비밀글

이전 1 ··· 175 176 177 178 179 180 181 182 183 ··· 185 다음


Recursive functions, without limits, could call themselves indefinitely. If you write a recursive function that executes over a certain number of iterations, you’ll encounter the “maximum recursion depth exceeded in comparison” Python error.

This guide discusses what this error means and why it is important. We’ll walk through an example of this error so you can learn how to fix it in your program.

maximum recursion depth exceeded in comparison

Recursive functions are functions that call themselves to find a solution to a program.

Well-written recursive functions include limits to ensure they do not execute infinitely. This may mean that a function should only run until a particular condition is met.

If you write a recursive function that executes more than a particular number of iterations (usually 997), you’ll see an error when you get to the next iteration.

This is because Python limits the depth of a recursion algorithm. This refers to how many times the function can call itself.

You can view the recursion limit in your Python shell using this code:

import sys print(sys.getrecursionlimit())

An Example Scenario

Let’s write a recursive function that calculates a number in the Fibonacci Sequence. In the Fibonacci Sequence, the next number in the sequence is the sum of the last two numbers. The first two numbers in the sequence are 0 and 1.

Here is a recursive function that calculates the Fibonacci Sequence:

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

If the number we specify is less than or equal to 1, that number is returned. Otherwise, our program calculates the next number in the sequence.

Next, we’re going to call our function:

print(fibonacci(5000))

This code calculates the number after the 5,000th number in the Fibonacci Sequence. Let’s run our code and see what happens:

Traceback (most recent call last): File "main.py", line 7, in <module> print(recur_fibo(5000)) File "main.py", line 5, in recur_fibo return(recur_fibo(n-1) + recur_fibo(n-2)) … File "main.py", line 2, in recur_fibo if n <= 1: RecursionError: maximum recursion depth exceeded in comparison

Our code returns a long error message. This message has been shortened for brevity.

The Solution

Python has raised a recursion error to protect us against a stack overflow. This is when the pointer in a stack exceeds the stack bound. Without this error, our program would try to use more memory space than was available.

Recursionerror: maximum recursion depth exceeded while calling a python object

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest
First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

We can fix this error by either making our sequence iterative, or by increasing the recursion limit in our program.

Solution #1: Use an Iterative Algorithm

We can change our program to use an iterative approach instead of a recursive approach:

to_calculate = 5 i = 0 next = 1 current = 1 last = 0 while i < to_calculate: next = current + last current = last last = next i += 1

This code calculates the first five numbers in the Fibonacci Sequence. We could increase the number of values we calculate but that would also increase the time it takes for our program to execute. Our program returns:

1

1

2

3

5

This approach bypasses the recursion error because we do not use recursive functions. Instead, we use a while loop to calculate the next number in the list.

Solution #2: Increase Recursion Limit

You can override the default recursion limit Python sets using the setrecursionlimit() method:

import sys sys.setrecursionlimit(5000)

This code sets the maximum recursion depth to 5,000. You should be careful when you use this method because it may cause a stack overflow depending on the resources available to the Python interpreter.

Recursionerror: maximum recursion depth exceeded while calling a python object

"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"

Venus, Software Engineer at Rockbot

In general, it is best to rewrite a function to use an iterative approach instead of increasing the recursion limit.

Conclusion

The “maximum recursion depth exceeded in comparison” error is raised when you try to execute a function that exceeds Python’s built in recursion limit. You can fix this error by rewriting your program to use an iterative approach or by increasing the recursion limit in Python.

Now you have the knowledge you need to fix this error like a pro!

How do I fix RecursionError maximum recursion depth exceeded while calling a Python object?

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.

How do you fix RecursionError maximum recursion depth exceeded?

The “maximum recursion depth exceeded in comparison” error is raised when you try to execute a function that exceeds Python's built in recursion limit. You can fix this error by rewriting your program to use an iterative approach or by increasing the recursion limit in Python.

How do you fix a recursion error in Python?

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 does Python handle maximum recursion depth?

The Python interpreter limits the recursion limit so that infinite recursions are avoided. The “sys” module in Python provides a function called setrecursionlimit() to modify the recursion limit in Python. It takes one parameter, the value of the new recursion limit. By default, this value is usually 10^3.