Table of contents
Namaste Coders π©βπ»
Before starting have a glance on the below article to know about functions in Python π
Built-in Functions User Defined Functions Lambda Functions
What is Recursion π€?
Recursion is simply self calling of a function. It is a technique of writing a function. In recursion we divide complex problem into simpler problem and than we find a solution for simpler problem which leads to solving the complex problem.
In recursion We have to think of following to solve a problem π
- Base case: It will end the recursion and will provide the required answer
- Simpler solution: It will lead towards complex problem solution.
Stacks are used behind the scene in recursion.
Example: We are going to learn how to find the factorial of a number. Suppose we need to find factorial of 5. 5!=54321
Recursively: Letβs make a function fact(num) which will take num as a parameter.
Simpler Solution: fact(num)=num*fact(num-1)
Base Case: if num=1 return 1
# Factorial of a number recursively
def fact(num):
if(num==1):
return 1
ans=num*fact(num-1)
return ans
num=5
ans=fact(num)
print("Factorial is :",num)
#Output:
#Factorial is : 5
Here is the tree structure of recursion. First, we go forward till the base case is hit. Then, it moves backward resulting into the output
Here is the stack which is created in the memory π
For more reference do watch the video tutorial
P.S. : Will continue with the functions and discuss more in upcoming articles. Stay tunedπ§
The End
I hope you enjoyed the article and had a good learning experience.
Follow for more articles and keep sharingπ©
Keep coding