Runtimeerror: Maximum Recursion Limit Reached in Python
Last Updated : 16 Feb, 2024
In this article, we will elucidate the Runtimeerror: Maximum Recursion Limit Reached In Python through examples, and we will also explore potential approaches to resolve this issue.
What is Runtimeerror: Maximum Recursion Limit Reached?
When you run a Python program you may see Runtimeerror: Maximum Recursion Limit Reached. It indicates that the execution of your program has surpassed the recursion limit of the Python interpreter. This typically occurs when a function calls itself recursively, and the recursion doesn't have a proper stopping condition (base case).
Syntax :
RecursionError: maximum recursion depth exceeded
Why does Runtimeerror: Maximum Recursion Limit Reached occur?
There are various reasons for Runtimeerror: Maximum Recursion Limit Reached in Python. Here we are explaining some common reasons for the occurrence of Runtimeerror: Maximum Recursion Limit Reached:
- Missing Base Case
- Infinite Recursion
- Exceeding Maximum Recursion Depth
Missing Base Case
As we all know the recursive function should include a base case that defines when the recursion should stop. However when we do not specify a base case, the function may keep calling itself indefinitely, leading to a Runtimeerror: Maximum Recursion Limit Reached
Python3 def endless_recursion(n): """A recursive function without a proper base case""" return n * endless_recursion(n-1) print(endless_recursion(5))
Output
File "Solution.py", line 3, in endless_recursion
return n * endless_recursion(n-1)
File "Solution.py", line 3, in endless_recursion
return n * endless_recursion(n-1)
File "Solution.py", line 3, in endless_recursion
return n * endless_recursion(n-1)
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
Infinite Recursion
This occurs when we incorrectly define recursive logic and it fails to make progress towards the base case can result in infinite recursion. This exhausts the call stack and results into 'RuntimeError: Maximum Recursion Limit Reached'
Python3 def countdown(n): if n > 0: # Here we dont reduce n so it leads to infinite loop print(n) countdown(n) # Example usage with n=5 n=5 countdown(n)
Output
File "Solution.py", line 5, in countdown
countdown(n)
File "Solution.py", line 5, in countdown
countdown(n)
[Previous line repeated 994 more times]
File "Solution.py", line 4, in countdown
print(n)
RecursionError: maximum recursion depth exceeded while getting the str of an object
Exceeding Maximum Recursion Depth
In Python, there is a limit on the maximum recursion depth to prevent stack overflow.If a recursive function exceeds this limit, Python raises a 'RuntimeError: Maximum Recursion Limit Reached'.
Python3 def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) # Testing the factorial function result = factorial(1001) print(result)
Output
Here we are calling factorial with a large value of n, that why we encounter a RecursionError.
File "Solution.py", line 5, in factorial
return n * factorial(n-1)
File "Solution.py", line 5, in factorial
return n * factorial(n-1)
[Previous line repeated 995 more times]
File "Solution.py", line 2, in factorial
if n == 0:
RecursionError: maximum recursion depth exceeded
Fix RuntimeError: Maximum Recursion Limit Reached
Below are some of the ways by which we can fix RuntimeError: Maximum Recursion Limit Reached in Python:
- Adding a base case
- Increasing the recursion limit
- Using an iterative approach
Adding a Base Case
One effective way to prevent RuntimeError: Maximum Recursion Limit Reached is to ensure that the recursive function has a proper stopping condition, commonly referred to as a base case. This ensures that the recursion stops when a certain condition is met.
Python3 def factorial_recursive_with_base_case(n): # Base case: when n is 0, return 1 if n == 0: return 1 # Recursive call return n * factorial_recursive_with_base_case(n - 1) if __name__ == '__main__': # Example: calculating the factorial of 100 result = factorial_recursive_with_base_case(100) print(result)
Output
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Increase Recursion Limit
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. If you are dealing with large inputs, you can set it to, 10^6 so that large inputs can be handled without any errors.
Python3 # importing the sys module import sys sys.setrecursionlimit(10**6) def fact(n): if(n == 0): return 1 return n * fact(n - 1) if __name__ == '__main__': # taking input f = 1001 print(fact(f))
Output40278964733717086731724613635692698970509423907492534717634371034036845091102764961263625269545637420528046859880739325469029853986780336746022515349961453558842192859116083367874245135491592125229928...
Using Iteration Instead of Recursion
Another effective way to address RuntimeError: Maximum Recursion Limit Reached is to convert the recursive solution into an iterative one, using loops instead of recursive calls.
Python3 # Function to calculate the factorial of a number using an iterative approach def factorial_iterative(n): # Initialize the result to 1 result = 1 # Iterate from 1 to n (inclusive) for i in range(1, n + 1): # Multiply the current result by the current value of i result *= i # Return the final result after the loop return result #Examples result = factorial_iterative(1001) print(result)
Output40278964733717086731724613635692698970509423907492534717634371034036845091102764961263625269545637420528046859880739325469029853986780336746022515349961453558842192859116083367874245135491592125229928...
Conclusion
In this article we discussed about ways How To Fix Obscure Runtimeerror: Maximum Recursion Limit Reached in Python. It involves understanding its root causes, such as missing base cases or improper recursive logic. By incorporating base cases, adjusting recursive logic, or switching to iterative approaches, developers can effectively resolve the error and ensure that recursive functions terminate appropriately, preventing infinite loops and stack overflow.
Similar Reads
Python | Handling recursion limit
When you execute a recursive function in Python on a large input ( > 10^4), you might encounter a "maximum recursion depth exceeded error". This is a common error when executing algorithms such as DFS, factorial, etc. on large inputs. This is also common in competitive programming on multiple pla
4 min read
SyntaxError: âreturnâ outside function in Python
We are given a problem of how to solve the 'Return Outside Function' Error in Python. So in this article, we will explore the 'Return Outside Function' error in Python. We will first understand what this error means and why it occurs. Then, we will go through various methods to resolve it with examp
4 min read
Python Program to Display Fibonacci Sequence Using Recursion
We are given a task to write the Fibonacci sequence using recursion. we will take the range as input of integer and then print the Fibonacci Sequence. In this article, we will see the method of Python Program to Display Fibonacci Sequence Using Recursion. Example: Input: n = 9Output: 0 1 1 2 3 5 8 1
2 min read
How to Fix - Timeouterror() from exc TimeoutError in Python
We can prevent our program from getting stalled indefinitely and gracefully handle it by setting timeouts for external operations or long-running computations. Timeouts help in managing the execution of tasks and ensuring that our program remains responsive. In this article, we will see how to catch
3 min read
Binary Search (Recursive and Iterative) - Python
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Below is the step-by-step algorithm for Binary Search:
6 min read
Python Program to Flatten a Nested List using Recursion
Given a nested list, the task is to write a python program to flatten a nested list using recursion. Examples: Input: [[8, 9], [10, 11, 'geeks'], [13]] Output: [8, 9, 10, 11, 'geeks', 13] Input: [['A', 'B', 'C'], ['D', 'E', 'F']] Output: ['A', 'B', 'C', 'D', 'E', 'F'] Step-by-step Approach: Firstly,
3 min read
Python Program to Find the Total Sum of a Nested List Using Recursion
A nested list is given. The task is to print the sum of this list using recursion. A nested list is a list whose elements can also be a list. Examples : Input: [1,2,[3]] Output: 6 Input: [[4,5],[7,8,[20]],100] Output: 144 Input: [[1,2,3],[4,[5,6]],7] Output: 28 Recursion: In recursion, a function ca
5 min read
Python | Maximum Sum Sublist
The task is to find a contiguous sublist (i.e., a sequence of elements that appear consecutively in the original list) such that the sum of the elements in this sublist is as large as possible. We need to return the maximum sum of this sublist. Let's explore methods to find Maximum Sum Sublist in py
2 min read
Python Runtimeerror: Super() No Arguments
Python, a versatile programming language, provides developers with a powerful toolset for creating complex applications. However, like any programming language, it comes with its share of challenges. One such issue that developers might encounter is the "RuntimeError: super(): no arguments." This er
4 min read
Loop Through a List using While Loop in Python
In Python, the while loop is a versatile construct that allows you to repeatedly execute a block of code as long as a specified condition is true. When it comes to looping through a list, the while loop can be a handy alternative to the more commonly used for loop. In this article, we'll explore fou
3 min read