Introduction to Recursive approach using Python
In this tutorial, we will learn how to think of a recursive solution for any problem in Python.
Certainly, Recursion is not an easy method to master. It takes time.
But after going through this article, it would be easier for you to understand what it is.
Recursion in Python is not different to any other language as it is a concept.
What is Recursion!
Basically, Recursion is a technique to call the same function inside its function definition to acquire the desired result.
Was it hard to understand-?
Lets’s see this example.
def fun(): print ("Hello") fun() # calling same function inside its function definition fun() # calling from main method
Hello Hello ......
This program will run infinitely and goes on printing Hello.
Obviously, it needs to stop at some point. That is where the concept of base-case arises.
Certainly, now to write a recursive program, these two steps are very critical.
- Base-Case: A condition written in a function definition to stop the recursion. The calling of the function stops at this point.
- Recurrence-Relation: It involves writing a relational based code to call the function with some modifications based on the present value.
No problem, if the above definitions went over your head. Just take a look at these examples.
Suppose I want to print Hello Jagan 5 times.
Have a look at the Recursive approach for this. One will surely understand the above two topics related to the base case and Recurrence Relation.
Python Program to print some text using recursion
def fun(i): if i>=n: # base case (recursion stops here) . return else: print ("Hello Jagan") # the below code is the Recurrence relation fun(i+1) # calling same function but with some modification that takes nearer to base case. n = 5 # you can take this value dynamically also i=0 fun(i)
Output : Hello Jagan Hello Jagan Hello Jagan Hello Jagan Hello Jagan
I hope, this clears the basics of how to write a recursive program. One should understand the power of recursion and
I would post many other programs regarding recursion to show its power to solve problems.
Leave a Reply