How To Fix Recursionerror In Python
Last Updated :
02 Feb, 2024
In this article, we will elucidate the Recursionerror In Python through examples, and we will also explore potential approaches to resolve this issue.
What is Recursionerror In Python?
When you run a Python program you may see Recursionerror. So what is Recursionerror In Python? Python RecursionError exception is raised when the execution of your program exceeds 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).
Why does Recursionerror occur?
There are various reasons for Recursionerror in Python. Here we are explaining some common reasons for occurring Recursionerror:
- 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 'RecursionError.'
Python3
def endless_recursion(n):
"""A recursive function without a proper base case"""
return n * endless_recursion(n-1)
print(endless_recursion(5))
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 5, in <module>
print(endless_recursion(5))
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 'RecursionError.'
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)
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 8, in <module>
countdown(n)
File "Solution.py", line 5, in countdown
countdown(n)
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 'RecursionError.'
Python3
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
# Testing the factorial function
result = factorial(1001)
print(result)
Here we are calling factorial with a large value of n, that why we encounter a RecursionError.
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 8, in <module>
result = factorial(500000)
File "Solution.py", line 5, in factorial
return n * factorial(n-1)
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 "RecursionError: Maximum Recursion Depth Exceeded" Error In Python
Below are some of the ways by which we can fix RecursionError in Python:
- Adding a base case
- Increasing the recursion limit
- Using an iterative approach
Adding a Base Case
One effective way to prevent RecursionError 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))
Output:
4027896473371708673172461363569269897050942390749253471763437103403684509110276496126362526954563742052804685988073932546902985398678033674602251534996145355884219285911608336787424513549159212522992854569462713969958504379595406450196963727411427873474502813253243738244563002268716094314978269894891095227257916911679456985092824215386329665233766798918236969009820752...................................................
Using Iteration Instead of Recursion
Another effective way to address RecursionError 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)
Output:
4027896473371708673172461363569269897050942390749253471763437103403684509110276496126362526954563742052804685988073932546902985398678033674602251534996145355884219285911608336787424513549159212522992854569462713969958504379595406450196963727411427873474502813253243738244563002268716094314978269894891095227257916911679456985092824215386329665233766798918236969009820752...................................................
Conclusion
In this article we discussed about 'RecursionError' in Python involves understanding the root cause, which may include missing base cases or improper recursive logic. By incorporating base cases and adjusting recursive logic, developers can effectively fix 'RecursionError' and ensure that recursive functions terminate appropriately, preventing infinite loops and stack overflow.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read