The Wayback Machine - https://web.archive.org/web/20240717180321/https://www.geeksforgeeks.org/recursion-in-python/
Open In App

Recursion in Python

Last Updated : 24 Nov, 2022
Improve
Suggest changes
Post a comment
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 | 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
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
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
Tail recursion to calculate sum of array elements.
Given an array A[], we need to find the sum of its elements using Tail Recursion Method. We generally want to achieve tail recursion (a recursive function where recursive call is the last thing that function does) so that compilers can optimize the code. Basically, if recursive call is the last statement, the compiler does not need to save the stat
3 min read
Generating subarrays using recursion
Given an array, generate all the possible subarrays of the given array using recursion. Examples: Input : [1, 2, 3] Output : [1], [1, 2], [2], [1, 2, 3], [2, 3], [3] Input : [1, 2] Output : [1], [1, 2], [2] We have discussed iterative program to generate all subarrays. In this post, recursive is discussed. Approach: We use two pointers start and en
6 min read
Generating all possible Subsequences using Recursion including the empty one.
Given an array. The task is to generate and print all of the possible subsequences of the given array using recursion. Examples: Input : [1, 2, 3] Output : [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3], [] Input : [1, 2] Output : [2], [1], [1, 2], [] Approach: For every element in the array, there are two choices, either to include it in the sub
5 min read
Tail Recursion in Scala
Recursion is a method which breaks the problem into smaller subproblems and calls itself for each of the problems. That is, it simply means function calling itself. The tail recursive functions better than non tail recursive functions because tail-recursion can be optimized by compiler. A recursive function is said to be tail recursive if the recur
3 min read
What is Tail Recursion
Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. For example the following C++ function print() is tail recursive. C/C++ Code // An example of tail recursive function void print(int n) { if (n &lt; 0
8 min read
Introduction to Recursion
What is Recursion? The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Gr
15+ min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Practice Tags :
three90RightbarBannerImg