Open In App

Python | Handling recursion limit

Last Updated : 26 May, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 platforms when you are trying to run a recursive algorithm on various test cases. 
In this article, we shall look at why this error occurs and how to handle it in Python. To understand this, we need to first look at tail recursion.
Tail recursion
In a typical recursive function, we usually make the recursive calls first, and then take the return value of the recursive call to calculate the result. Therefore, we only get the final result after all the recursive calls have returned some value. But in a tail recursive function, the various calculations and statements are performed first and the recursive call to the function is made after that. By doing this, we pass the results of the current step to the next recursive call to the function. Hence, the last statement in a Tail recursive function is the recursive call to the function. 
This means that when we perform the next recursive call to the function, the current stack frame (occupied by the current function call) is not needed anymore. This allows us to optimize the code. We Simply reuse the current stack frame for the next recursive step and repeat this process for all the other function calls.
Using regular recursion, each recursive call pushes another entry onto the call stack. When the functions return, they are popped from the stack. In the case of tail recursion, we can optimize it so that only one stack entry is used for all the recursive calls of the function. This means that even on large inputs, there can be no stack overflow. This is called Tail recursion optimization.
Languages such as lisp and c/c++ have this sort of optimization. But, the Python interpreter doesn’t perform tail recursion optimization. Due to this, the recursion limit of python is usually set to a small value (approx, 10^4). This means that when you provide a large input to the recursive function, you will get an error. This is done to avoid a stack overflow. The Python interpreter limits the recursion limit so that infinite recursions are avoided. 
  
Handling 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.
Example:
Consider a program to compute the factorial of a number using recursion. When given a large input, the program crashes and gives a “maximum recursion depth exceeded error”.
 

Python3




# A simple recursive function
# to compute the factorial of a number
def fact(n):
 
    if(n == 0):
        return 1
 
    return n * fact(n - 1)
 
 
if __name__ == '__main__':
 
    # taking input
    f = int(input('Enter the number: \n'))
 
    print(fact(f))


Output : 
 

Using the setrecursionlimit() method, we can increase the recursion limit and the program can be executed without errors even on large inputs.
 

Python3




# importing the sys module
import sys
 
# the setrecursionlimit function is
# used to modify the default recursion
# limit set by python. Using this,
# we can increase the recursion limit
# to satisfy our needs
 
sys.setrecursionlimit(10**6)
 
# a simple recursive function
# to compute the factorial of a number
# it takes one parameter, the
# number whose factorial we
# want to compute and returns
# its factorial
def fact(n):
 
    if(n == 0):
        return 1
 
    return n * fact(n - 1)
 
if __name__ == '__main__':
 
    # taking input
    f = int(input('Enter the number: \n'))
 
    print(fact(f))


Output : 
 

 



Similar Reads

Runtimeerror: Maximum Recursion Limit Reached in Python
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 exe
5 min read
Python - Split Dictionary values on size limit of values
Given a dictionary with string values, the task is to write a python program to split values if the size of string exceeds K. Input : {1 : "Geeksforgeeks", 2 : "best for", 3 : "all geeks"}, limit = 5Output : {1: 'Geeks', 2: 'forge', 3: 'eks', 4: 'best ', 5: 'for', 6: 'all g', 7: 'eeks'}Explanation : All string values are capped till length 5. New v
8 min read
Python | sympy.limit() method
With the help of sympy.limit() method, we can find the limit of any mathematical expression, e.g., [Tex]\begin{equation} \lim_{x\to a} f(x) \end{equation} [/Tex] Syntax: limit(expression, variable, value)Parameters: expression - The mathematical expression on which limit operation is to be performed, i. e., f(x). variable - It is the variable in th
1 min read
Python MySQL - Limit Clause
A connector is employed when we have to use MySQL with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and MySQL Server. Python-MySQL-Connector This is a MySQL Connector that allows Python to access MySQL Driver a
2 min read
Python MongoDB - Limit Query
MongoDB is one of the most used databases with its document stored as collections. These documents can be compared to JSON objects. PyMongo is the Python driver for mongoDB. Limit() Method: The function limit() does what its name suggests- limiting the number of documents that will be returned. There is only one argument in the parameter which is a
2 min read
Python MariaDB - Limit Clause using PyMySQL
The Limit clause is used in SQL to control or limit the number of records in the result set returned from the query generated. By default, SQL gives out the required number of records starting from the top but it allows the use of the OFFSET keyword. OFFSET allows you to start from a custom row and get the required number of result rows. Syntax : S
2 min read
How to Set the X and the Y Limit in Matplotlib with Python?
In this article, we will learn how to set the X limit and Y limit in Matplotlib with Python. Matplotlib is a visualization library supported by Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year
2 min read
Python SQLite - LIMIT Clause
In this article, we are going to discuss the LIMIT clause in SQLite using Python. But first, let's get a brief about the LIMIT clause. If there are many tuples satisfying the query conditions, it might be resourceful to view only a handful of them at a time. LIMIT keyword is used to limit the data given by the SELECT statement. Syntax: SELECT colum
2 min read
Python PostgreSQL - Limit Clause
In this article, we are going to see how to use the limit clause in PostgreSQL using pyscopg2 module in Python. In PostgreSQL LIMIT constraints the number of rows returned by the query. By default, It is used to display some specific number of rows from the top. If we want to skip a number of rows before returning the rows then we use the OFFSET cl
2 min read
How to set an input time limit in Python?
In this article, we will explain how to set an input time limit in Python. It is one of the easiest programming languages which is not only dynamically typed but also garbage collected. Here we will look at different methods to set an input time limit. Below are the methods we will use in this article. Methods to Set an Input Time Limit in PythonUs
6 min read
How to limit the width and height in Pygal?
Prerequisites: pygal Pygal is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. While making a plot it is important for us to optimize its size. In this article, we will see how we can resize the plot window in the Pygal module. Here are various ways to change the d
2 min read
PyQt5 - Setting limit to number of items in ComboBox
In this article we will see how we can set limit to the number of items in the combo box. When we create a combo box there is no limit set to the items we can add any number of items although sometimes condition arises to set the maximum limit to the items. In order to set the maximum limit to the number of items we use setMaxCount method. Syntax :
2 min read
PyQt5 - How to know maximum number of items limit in ComboBox
In this article we will see how we can know maximum number limit of items in the combo box. When we create a combo box there is no limit set to the items we can add any number of items although sometimes condition arises to set the maximum limit to the items. In order to set the maximum limit to the number of items we use setMaxCount method. In ord
2 min read
PostgreSQL - LIMIT clause
The PostgreSQL LIMIT clause is a handy tool used to fetch a specific subset of rows returned by a query. This clause is optional and can be a powerful way to control the amount of data your query returns, especially when working with large datasets. Let us better understand the LIMIT Clause in PostgreSQL from this article. SyntaxSELECT * FROM table
2 min read
Limit the Maximum Value of a Numeric Field in a Django Model
Limiting the maximum value of a numeric field in a Django model is essential for maintaining data integrity and preventing errors. By using Django’s built-in validators like MaxValueValidator, implementing custom validation logic in the clean method, and applying constraints in forms, you can ensure that your application handles numeric data effect
3 min read
PostgreSQL - LIMIT with OFFSET clause
The PostgreSQL LIMIT clause is a powerful feature that allows users to retrieve a specific subset of rows from query results. This optional clause can be paired with the OFFSET clause to skip a specified number of rows before returning the desired results. Such functionality is particularly beneficial for pagination, enabling us to fetch data in ma
4 min read
Handling missing keys in Python dictionaries
In Python, dictionaries are containers that map one key to its value with access time complexity to be O(1). But in many applications, the user doesn't know all the keys present in the dictionaries. In such instances, if the user tries to access a missing key, an error is popped indicating missing keys. Handling Missing Keys in Python DictionariesI
4 min read
SQL using Python | Set 3 (Handling large data)
It is recommended to go through SQL using Python | Set 1 and SQL using Python and SQLite | Set 2 In the previous articles the records of the database were limited to small size and single tuple. This article will explain how to write & fetch large data from the database using module SQLite3 covering all exceptions. A simple way is to execute th
4 min read
Handling PostgreSQL BLOB data in Python
In this article, we will learn how to Handle PostgreSQL BLOB data in Python. BLOB is a Binary large object (BLOB) is a data type that can store any binary data.To store BLOB data in a PostgreSQL database, we need to use the Binary Large Object (BLOB) data type.By using the Binary Large Object (BLOB) data type, we can store any binary data in a Post
5 min read
Multiple Exception Handling in Python
Given a piece of code that can throw any of several different exceptions, and one needs to account for all of the potential exceptions that could be raised without creating duplicate code or long, meandering code passages. If you can handle different exceptions all using a single block of code, they can be grouped together in a tuple as shown in th
3 min read
Python | Handling no element found in index()
Sometimes, while working with Python lists, we are confronted with a problem in which we need to check whether an element is present in a list and also where exactly, which index it occurs. The convenient solution of it is to use index(). But problem with this can come that sometimes, the desired element might not be present in the list. Let's disc
5 min read
Python IMDbPY - Error Handling
In this article we will see how we can handle errors related to IMDb module of Python, error like invalid search or data base error network issues that are related to IMDbPY can be caught by checking for the imdb.IMDbErrorexceptionIn order to handle error we have to import the following from imdb import IMDbError Syntax : try : # code except IMDbEr
2 min read
Handling mails with EZGmail module in Python
EZGmail is a Python module that can be used to send and receive emails through Gmail. It works on top of the official Gmail API. Although EZGmail does not cover everything that can be done with the Gmail API, it makes the common tasks very simple which are a lot more complicated using Google's own API. In this article, we will take a look at how to
4 min read
Handling TypeError Exception in Python
TypeError is one among the several standard Python exceptions. TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise a TypeError. ExamplesThe general causes for TypeError being raised are: 1. Unsupported Operation Betwe
3 min read
Python VLC MediaPlayer – Enabling Mouse Input Handling
In this article we will see how we can enable mouse input handling the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. By input
2 min read
Handling OSError exception in Python
Let us see how to handle OSError Exceptions in Python. OSError is a built-in exception in Python and serves as the error class for the os module, which is raised when an os specific system function returns a system-related error, including I/O failures such as "file not found" or "disk full". Below is an example of OSError: Python Code # Importing
2 min read
Handling a thread's exception in the caller thread in Python
Multithreading in Python can be achieved by using the threading library. For invoking a thread, the caller thread creates a thread object and calls the start method on it. Once the join method is called, that initiates its execution and executes the run method of the class object. For Exception handling, try-except blocks are used that catch the ex
3 min read
Handling EOFError Exception in Python
EOFError is raised when one of the built-in functions input() or raw_input() hits an end-of-file condition (EOF) without reading any data. This error is sometimes experienced while using online IDEs. This occurs when we have asked the user for input but have not provided any input in the input box. We can overcome this issue by using try and except
1 min read
Error Handling in Python using Decorators
Decorators in Python is one of the most useful concepts supported by Python. It takes functions as arguments and also has a nested function. They extend the functionality of the nested function. Example: C/C++ Code # defining decorator function def decorator_example(func): print("Decorator called") # defining inner decorator function def
2 min read
Handling timezone in Python
There are some standard libraries we can use for timezones, here we'll use pytz. This library has a timezone class for handling arbitrary fixed offsets from UTC and timezones. Installation pytz is a third-party package that you have to install. To install pytz use the following command - pip install pytz Getting Started After installation import th
4 min read
Practice Tags :
three90RightbarBannerImg