Content |
---|
What is Recursion? |
Why do we need Recursion? |
How to write Recursion in 3 steps? |
Problems |
Recursion is a way of solving a problem by having a function calling itself.
def recursionMethod (parameters):
if exit from condition satisfied:
return some value
else:
recursionMethod (modified parameters)
-
Performing the same operation multiple times with different inputs.
-
In every step, we try smaller inputs to make the problem smaller.
-
Base condition is needed to stop the recursion, otherwise infinite loop will occur.
Importance of base condition
A programmer's wife tells him as he leaves the house: "While you're out, buy some milk." He never returns home and the universe runs out of milk. 🤣🤣🤣
-
Recursion is made for solving problems that can be broken down into smaller, repetitive problems. It is especially good for working on things that have many possible branches and are too complex for an iterative approach.
-
Using recursion makes the code clearer.
-
The prominent usage of recursion in data structures like Trees and Graphs.
-
It is used in many algorithms (Divide and Conquer, Greedy and Dynamic Programming).
Let's take the example of finding factorial.
Step 1: Recursive case - the flow
So, the Recursive case can be
Step 2: Base case - the stopping criterion
In case of factorial of any number, base condition would be:
Step 3: Unintentional case - the constraint
As factorial of decimals or negative integers can't be calculated, we need to handle it.
After following all the above 3 steps, our code will look like below:
def factorial(n):
assert n >= 0 and int(n) == n, 'The number must be positive integer only!'
if n in [0,1]:
return 1
else:
return n * factorial(n-1)
Let's follow the similar approach and write steps for Fibonacci Numbers
Step 1: Recursive case - the flow
Step 2: Base case - the stopping criterion
0 & 1
Step 3: Unintentional case - the constraint
After following all the above 3 steps, our code will look like below:
def fibonacci(n):
assert n >=0 and int(n) == n, "Fibonacci number cannot be negative number or non integer
if n in [0,1]:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
To learn more about Recursion, follow below links:
- Sum of digits of a number using recursion
- Power of given number using recursion
- GCD of two given numbers using recursion
- Decimal to binary conversion using recursion
- Product of array
- Recursive range
- Reverse array
- Palindrome
- Some recursive
- Flatten array
- Capitalize first
- Nested even sum
- Capitalize words
- Stringify numbers
- Collect strings
- Total handshakes