Tensorflow RecursionError maximum recursion depth exceeded while calling a Python object

RecursionError

RecursionError는 재귀와 관련된 에러입니다. 가장 많이 발생하는 이유는 Python이 정한 최대 재귀 깊이보다 재귀의 깊이가 더 깊어질 때입니다.

Python이 정한 최대 재귀 깊이는 sys.getrecursionlimit()을 이용해 확인할 수 있습니다. BOJ의 채점 서버에서 이 값은 1,000으로 되어 있습니다.

소스 1. n을 입력받고, 1부터 n까지 합을 재귀 함수로 구하는 소스

calc(n)을 호출하면 총 n+1번의 재귀 호출이 발생합니다. print(calc(n))으로 함수를 호출하고 있기 때문에, print(calc(n))의 재귀의 깊이는 n+2가 됩니다. 따라서, n < 998의 경우에는 RecursionError가 발생하지 않지만, n ≥ 998부터는 RecursionError가 발생하게 됩니다. 998 이상의 값을 넣었을 때 런타임 에러 메시지는 다음과 같습니다.

Traceback (most recent call last): File "Main.py", line 8, in <module> print(calc(n)) File "Main.py", line 5, in calc return n + calc(n-1) File "Main.py", line 5, in calc return n + calc(n-1) File "Main.py", line 5, in calc return n + calc(n-1) [Previous line repeated 995 more times] File "Main.py", line 2, in calc if n == 0: RecursionError: maximum recursion depth exceeded in comparison

이 에러를 해결하는 방법은 2가지가 있습니다.

첫 번째는 재귀 함수를 사용하지 않는 것입니다. 소스 1은 소스 2와 같이 재귀 함수를 사용하지 않는 방법으로도 구현할 수 있습니다.

소스 2. 소스 1을 반복문을 사용하게 변경한 소스

DFS를 이용했다면 BFS로, 다이나믹 프로그래밍을 재귀로 구현했다면 반복문으로 구현하는 것 처럼 재귀를 사용하지 않게 구현하는 방법으로 해결할 수 있습니다.

두 번째는 sys.setrecursionlimit()을 사용하는 것입니다. 이 함수를 사용하면, Python이 정한 최대 재귀 갚이를 변경할 수 있습니다. 소스 1의 최대 재귀 깊이를 1,000,000 정도로 크게 설정하면 런타임 에러 없이 실행이 됩니다.

소스 3. 소스 1의 최대 재귀 깊이를 변경한 소스

sys.setrecursionlimit()로 설정할 수 있는 최댓값을 크게 변경했다고 하더라도, 재귀의 깊이가 채점 서버가 감당할 수 없는 정도로 깊어지면, Segmentation fault가 발생해 런타임 에러 이유로 SegFault를 받게됩니다.

소스 4. 소스 1의 최대 재귀 깊이를 매우 크게 변경한 소스

재귀의 깊이 제한이 10억까지 늘어났으니 입력으로 1억을 넣어도 올바르게 값을 구해야 합니다. 하지만, 이 깊이 제한은 채점 서버가 감당할 수 없는 값으로 Segmentation fault가 발생합니다.

sys.setrecursionlimit()으로 변경한 최대 깊이 제한이 너무 작을 때도 RecursionError가 발생합니다.

소스 5. 소스 1의 최대 재귀 깊이를 1로 변경한 소스

소스 5와 같이 10**6을 1**6으로 오타를 낸 경우라면, sys.setrecursionlimit(1)이 실행됩니다. 이 경우에도 RecursionError가 발생하며, 런타임 에러 메시지는 다음과 같습니다.

Traceback (most recent call last): File "Main.py", line 2, in <module> sys.setrecursionlimit(1) RecursionError: cannot set the recursion limit to 1 at the recursion depth 1: the limit is too low

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?
  • RecursionError: Maximum Recursion Depth Exceeded while calling a Python Object
  • RecursionError: Maximum Recursion Depth Exceeded While Calling A Python Object
  • Best practices to avoid RecursionError: Maximum Recursion Depth Exceeded while calling a Python Object
    • 1. Using other loops instead of recursion
    • 2. Using sys.setrecursionlimit() function
    • 3. Setting boundary conditions
    • 4. Creating a converging recursion
    • 5. Using Memoization

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:

import sys print(sys.getrecursionlimit())

The output is:

1000

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.

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

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

Factorial is : 120

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

print("Factorial is :", find_fact(5000))

Output:

RecursionError: maximum recursion depth exceeded in comparison

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.

def nested(n): list1 = list2 = [] for i in range(n): list1.append([]) list1 = list1[0] return list2 nestedlist = nested(2000) print(nestedlist)

The output will be a recursion error.

RecursionError: maximum recursion depth exceeded while getting the repr of an object

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

def find_fact(n): mul = 1 for i in range(2,n+1): mul = mul * i return mul print("Factorial is :", find_fact(1500))

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.

import sys sys.setrecursionlimit(2000)

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.

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

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 :

'if n == 1 or n == 0 : return 1'

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.

Until next time, Keep Learning!

  • [SOLVED] Python No Module Named Pil

  • [Fixed] ‘tensorflow.python.framework.ops’ has no attribute ‘_tensorlike’

  • [SOLVED] TypeError: “int” Object Is Not Callable

  • [Solved] TypeError: Unhashable Type: ‘slice’

zusammenhängende Posts

Toplist

Neuester Beitrag

Stichworte