Recursion in Python
The recursion concept in Python is explained through the factorial and the Fibonacci sequence.
# factorial(0) = 1
# factorial(1) = 1
# factorial(7) = 7*6*5*4*3*2*1
# factorial(7) = 7*factorial(6)
# factorial(7) = 7*6*factorial(5)
# factorial(7) = 7*6*5*factorial(4)
# factorial(7) = 7*6*5*4*factorial(3)
# factorial(7) = 7*6*5*4*3*factorial(2)
# factorial(7) = 7*6*5*4*3*2*factorial(1)
# factorial(7) = 7*6*5*4*3*2*1
# factorial(4) = 4*3*2*1
# factorial(n) = n*factorial(n-1)
def findFactorial(n):
if n==0 or n==1: return 1
else: return n * findFactorial(n-1)
print(findFactorial(5))
# fibonachi numbers sequence = 0 1 1 2 3 5 8 13 ....
def findFibonachiNo(n):
if n==0: return 0
elif n==1: return 1
else: return findFibonachiNo(n-1) + findFibonachiNo(n-2)
print(findFibonachiNo(6))
Comments
Post a Comment
Write something to CodeWithAbdur!