Open In App

Recursion in Python

Last Updated : 24 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The term Recursion can be defined as the process of defining something in terms of itself. In simple words, it is a process in which a function calls itself directly or indirectly. 

img 

Advantages of using recursion

  • A complicated function can be split down into smaller sub-problems utilizing recursion.
  • Sequence creation is simpler through recursion than utilizing any nested iteration.
  • Recursive functions render the code look simple and effective.

Disadvantages of using recursion

  • A lot of memory and time is taken through recursive calls which makes it expensive for use.
  • Recursive functions are challenging to debug.
  • The reasoning behind recursion can sometimes be tough to think through.

Syntax:

def func(): <--
              |
              | (recursive call)
              |
    func() ----

Example 1: A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8…. 

Python3




# Program to print the fibonacci series upto n_terms
 
# Recursive function
def recursive_fibonacci(n):
  if n <= 1:
      return n
  else:
      return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
 
n_terms = 10
 
# check if the number of terms is valid
if n_terms <= 0:
  print("Invalid input ! Please input a positive value")
else:
  print("Fibonacci series:")
for i in range(n_terms):
    print(recursive_fibonacci(i))


Output

Fibonacci series:
0
1
1
2
3
5
8
13
21
34

Example 2: The factorial of 6 is denoted as 6! = 1*2*3*4*5*6 = 720. 

Python3




# Program to print factorial of a number
# recursively.
 
# Recursive function
def recursive_factorial(n):
  if n == 1:
      return n
  else:
      return n * recursive_factorial(n-1)
 
# user input
num = 6
 
# check if the input is valid or not
if num < 0:
  print("Invalid input ! Please enter a positive number.")
elif num == 0:
  print("Factorial of number 0 is 1")
else:
  print("Factorial of number", num, "=", recursive_factorial(num))


Output

Factorial of number 6 = 720

What is Tail-Recursion?

A unique type of recursion where the last procedure of a function is a recursive call. The recursion may be automated away by performing the request in the current stack frame and returning the output instead of generating a new stack frame. The tail-recursion may be optimized by the compiler which makes it better than non-tail recursive functions. 

Is it possible to optimize a program by making use of a tail-recursive function instead of non-tail recursive function? 
Considering the function given below in order to calculate the factorial of n, we can observe that the function looks like a tail-recursive at first but it is a non-tail-recursive function. If we observe closely, we can see that the value returned by Recur_facto(n-1) is used in Recur_facto(n), so the call to Recur_facto(n-1) is not the last thing done by Recur_facto(n). 

Python3




# Program to calculate factorial of a number
# using a Non-Tail-Recursive function.
 
# non-tail recursive function
def Recur_facto(n):
   
    if (n == 0):
        return 1
   
    return n * Recur_facto(n-1)
   
# print the result
print(Recur_facto(6))


Output

720

We can write the given function Recur_facto as a tail-recursive function. The idea is to use one more argument and in the second argument, we accommodate the value of the factorial. When n reaches 0, return the final value of the factorial of the desired number. 

Python3




# Program to calculate factorial of a number
# using a Tail-Recursive function.
 
# A tail recursive function
def Recur_facto(n, a = 1):
   
    if (n == 0):
        return a
   
    return Recur_facto(n - 1, n * a)
   
# print the result
print(Recur_facto(6))


Output

720


Previous Article
Next Article

Similar Reads

Python | Handling recursion limit
When you execute a recursive function in Python on a large input ( &gt; 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 algo
4 min read
Python | All Permutations of a string in lexicographical order without using recursion
Write a python program to print all the permutations of a string in lexicographical order. Examples: Input : python Output : hnopty hnopyt hnotpy hnotyp hnoypt ...... ytpnho ytpnoh ytpohn ytponh Input : xyz Output : xyz xzy yxz yzx zxy zyx Method 1: Using the default library itertools function permutations. permutations function will create all the
2 min read
Python program to find the factorial of a number using recursion
A factorial is positive integer n, and denoted by n!. Then the product of all positive integers less than or equal to n. [Tex]n! = n*(n-1)*(n-2)*(n-3)*....*1 [/Tex] For example: [Tex]5! = 5*4*3*2*1 = 120 [/Tex] In this article, we are going to calculate the factorial of a number using recursion. Examples: Input: 5 Output: 120 Input: 6 Output: 720 I
1 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 calls itself repeatedly. This technique is generally
5 min read
Python program to find the power of a number using recursion
Given a number N and power P, the task is to find the power of a number ( i.e. NP ) using recursion. Examples: Input: N = 2 , P = 3Output: 8 Input: N = 5 , P = 2Output: 25 Approach: Below is the idea to solve the above problem: The idea is to calculate power of a number 'N' is to multiply that number 'P' times. Follow the below steps to Implement t
3 min read
When not to use Recursion while Programming in Python?
To recurse or not to recurse, that is the question. We all know about the fun we have with recursive functions. But it has its own set of demerits too, one of which is going to be explained in this article to help you choose wisely. Say, we need to create a function which when called needs to print the data in a linked list. This can be done in 2 w
3 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, we try to initialize a variable into the linked l
3 min read
Python Program to Flatten a List without using Recursion
The task is to convert a nested list into a single list in Python i.e no matter how many levels of nesting are there in the Python list, all the nested have to be removed in order to convert it to a single containing all the values of all the lists inside the outermost brackets but without any brackets inside. In other words, an element in a list c
7 min read
Tail Recursion in Python Without Introspection
These are the special type of recursive functions, where the last statement executed inside the function is the call to the function itself. Advantages of implementing Tail Recursive functionIn this concept, the compiler doesn't need to save the stack frame of the function after the tail-recursive call is executed.It uses less memory as compared to
4 min read
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
Practice Tags :
three90RightbarBannerImg