Recursion in Python
'''
Recursion in Python:
It is the process of defining something in terms of itself.
A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.
'''
'''
Python Recursive Functions:
In Python, we know that a function can call other functions.
It is even possible for the function to call itself.
These types of functions are termed as recursive functions.
'''
#factorial (7) = 7*6*5*4*3*2*1
#factorial (6) = 6*5*4*3*2*1
#factorial (5) = 5*4*3*2*1
#factorial (0) = 1
#factorial (n) = n * factorial (n-1)
def factorial(n):
if(n == 0 or n ==1):
return 1
else:
return n * factorial (n-1)
#Here we have called the function factorial (n-1) with function factorial (n).
print(factorial (3)) #output = 6
print(factorial (4)) #output = 24
print(factorial (5)) #output = 120
#5 * factorial(4)
#5 * 4 * factorial(3)
#5 * 4 * 3 * factorial(2)
#5 * 4 * 3 * 2 * factorial(1) Here if-statement will be executed.
#5 * 4 * 3 * 2 * 1
#According to Fibonacci Sequence,
#f(0) = 0
#f(1) = 1
#f(2) = f(1) + f(0)
#f(n) = f(n-1) + f(n-2)
#Write a program to print Fibonacci Sequence.
def Fibonacci(n):
if(n == 0):
return 0
elif(n == 1):
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
print(Fibonacci(8)) #output = 21
def Fibonacci(n):
if(n==0):
return 0
elif(n==1):
return 1
else :
return Fibonacci(n-1)+Fibonacci(n-2)
print(Fibonacci(10)) #output = 55
Comments
Post a Comment