Recursion

Last updated Aug 10, 2021

Recursion

Recursion in python is a process of repeating items again and again in a self-similar way. Basically, Recursion allows you to call a particular function inside the same function, and thus the function is known by the name of Recursive Function. In recursion, the function can call itself directly or indirectly.

Advantages of Recursion

  1. A complicated and big function can be split into small sub-problems with the help of recursion.

  2. Recursive functions make the code simple and effective.

 

Disadvantages of Recursion

  1. The functions which are created for recursion are proven challenging to debug.

  2. Recursive functions take a lot of memory and time for calling them.

The basic examples of Recursion are the Fibonacci series and the factorial of a number. Let's take a look at the example of Recursion:-

 

Fibonacci series through Recursion

So now we will take the example of Fibonacci series:-

def recursive_fibonacci(n):
    if n <= 1:
        return n
    else:
        return (recursive_fibonacci(n - 1) + recursive_fibonacci(n - 2))


n_terms = 10
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))
Fibonacci Series:   
0
1
1
2
3
5
8
13
21
34

As can see that we had obtained the Fibonacci series.

Factorial of a number using Recursion

Now we will find the factorial of a number in python with the help of recursion:-

def recursive_factorial(n):
    if n == 1:
        return n
    else:
        return n * recursive_factorial(n - 1)
num = 6
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))
Factorial of number 6 = 720

 

So we had obtained factorial of a number. 

Now we had got a brief knowledge about recursion function.

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

57 Views