Python Recursion

Learn with this blog how to work On Python Recursion Function and Examples.

Python Recursion:

A function is said to be a recursive if it calls itself. For example,  lets say we have a function abc() and in the body of abc() there is a call to the abc().

Python Recursion Example:

In this example we are defining a user-defined function factorial(). This function finds the factorial of a number by calling itself repeatedly until the base case(We will discuss more about base case later, after this example) is reached.

Python Recursion Example Programs:

Program 1

def factorial(n):
print(“factorial has been called with n = ” + str(n))
if n == 1:
return 1
else:
res = n * factorial(n-1)
print(“intermediate result for “, n, ” * factorial(” ,n-1, “): “,res)
return res
print(factorial(5))

Output:

factorial has been called with n = 5
factorial has been called with n = 4
factorial has been called with n = 3
factorial has been called with n = 2
factorial has been called with n = 1
intermediate result for 2 * factorial( 1 ): 2
intermediate result for 3 * factorial( 2 ): 6
intermediate result for 4 * factorial( 3 ): 24
intermediate result for 5 * factorial( 4 ): 120
120

Program 2:

def printFun(test):
if (test < 1):
return
else:
print( test, end = ” “)
printFun(test-1) # statement 2
print( test, end = ” “)
return
test = 3
printFun(test)

Output:

3 2 1 1 2 3

Why use recursion in programming?

We use recursion to break a big problem in small problems and those small problems into further smaller problems and so on. At the end the solutions of all the smaller subproblems are collectively helps in finding the solution of the big main problem.

Advantages of recursion:

1. Easier to write.
2. Readable – Code is easier to read and understand.
3. Reduce the lines of code – It takes less lines of code to solve a problem using recursion

Disadvantages of recursion:

1. Not all problems can be solved using recursion.
2. If you don’t define the base case then the code would run indefinitely.
3. Debugging is difficult in recursive functions as the function is calling itself in a loop and it is hard to understand which call is causing the issue.
4. Memory overhead – Call to the recursive function is not memory efficient.

Reference:

www.beginnersbook.com