Recursion in Python

Recursion in python

The process of defining something in terms of itself is recursion. Let’s understand recursion with a simple example. Do you remember going to the saloon where two parallel mirrors are facing each other?

When you look in Mirror A, you also see the images reflected on Mirror B, when you look in Mirror B you’ll see the images reflected on Mirror A. Images being reflected on both mirrors can be called recursion. I hope you all are now clear about the term recursion.

Recursion in Python Programming

When a function call itself is called a recursive function. We should know that recursion can be infinite but if we do not provide a specific condition (base case) to put an end to the recursion process system might get slow down or hang, hence python provides the limit of only 1000 recursive calls, but we can change and increase recursion limit using sys module, sys.setrecursionlimit(value)

Flowchart of recursive function

Python recursive function

Syntax of recursive function

Python recursive function syntax

Example of recursive function

Example of python recursive function

The output of the recursive function

Output of python recursive function

Let's understand the working how recursive function works

Here, I made a function named factorial(). It is a recursive function. This function is called after the input given by the user, it recursively calls itself by decreasing the number every time. Until an integer equals one, each function multiplies it by the factorial of the number below it. The following steps can be used to describe this recursive call.

factorial (7) #first call with 7

7*factorial(6) #second call with 6

7*6*factorial(5) #thirdcall with 5

7*6*5factorial(4) #fourth call with 4

7*6*5*4*factorial(3) #fifth call with 3

7*6*5*4*3*2*factorial(2) #sixth call with 2

7*6*5*4*3*2*factorial(1) #seventh call with 1

7*6*5*4*3*2*1 #return from the seventh call as number 1

7*6*5*4*3*2 #return from the sixth call as number 2

7*6*5*4*6 #return from the fifth call as number 6

7*6*5*24 #return from the fourth call as number 24

7*6*120 #return from the third call as number 120

7*720 #return from the second call as number 5040

5040 #return from the first call

The recursion ends when the number reduces to 1, and this is the base case for this program. A recursive function must have a base case that terminates or else the function calls itself infinite times.

Conclusion

The recursive function makes the code look clean but it takes a lot of memory and time. It might be difficult to debug while working on large projects. If a repetitive task is needed to be done, it can be done using recursive functions. You can also use loops instead of recursive functions to optimize memory.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Reply to