L34- Recursion
L34- Recursion
L34- Recursion
Recursion
In
Python
The CS Pundit
Function Recursion
Function recursion is a process in which a function calls itself directly or indirectly. It is
useful for solving problems that can be broken down into smaller subproblems of the
same kind. Recursion can make the code simpler and more elegant, but it can also be
inefficient and hard to debug.
To write a recursive function in Python, you need to follow some steps:
● Define a base case that will stop the recursion when it is met. This is usually a
simple condition that can be solved without recursion.
● Define a recursive case that will call the function again with a smaller or simpler
input. This should bring the input closer to the base case.
● Make sure that the recursive case does not call the function with the same input as
before, or else it will create an infinite loop.
● Return the result of the base case or the recursive case, depending on the input.
Recursion -Factorial of a number
5! = 5*4*3*2*1 n! = n*(n-1)!
4! = 4*3*2*1
3! = 3*2*1
2! = 2*1
1! = 1
0! = 1
5! = 5*4!
4! = 4*3!
3! = 3*2!
2! = 2*1!
1! = 1
0! = 1
Factorial of a number
Factorial of a number: The factorial of a number is the product of all the
integers from 1 to that number
def factorial(n):
if n == 0 or n ==1:
return 1
else:
return (n * factorial(n-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Recursion
The base case is when n is 0 or 1, in which case the factorial is 1.
The recursive case is when n is greater than 1, in which case the factorial is n
times the factorial of n - 1.