python program to Recursive implementation of a. Factorial b. Fibonacci c. Tower of Hanoi

in this tutorial we are learn about Recursive implementation of  Factorial, Fibonacci, Tower of Hanoi 

Some computer programming languages allow a module or function to call itself. This technique is known as recursion. In recursion, a function Î± either calls itself directly or calls a function Î² that in turn calls the original function Î±. The function Î± is called recursive function.


a. Factorial:
num = int(input("Enter a number: "))  
factorial = 1  
if num < 0:  
   print("Sorry, factorial does not exist for negative numbers")  
elif num == 0:  
   print("The factorial of 0 is 1")  
else:  
   for i in range(1,num + 1):  
       factorial = factorial*i  
   print("The factorial of",num,"is",factorial)

output:
Factorial

b. Fibonacci:
nterms = int(input("How many terms? "))


n1, n2 = 0, 1
count = 0


if nterms <= 0:
   print("Please enter a positive integer")
elif nterms == 1:
   print("Fibonacci sequence upto",nterms,":")
   print(n1)
else:
   print("Fibonacci sequence:")
   while count < nterms:
       print(n1)
       nth = n1 + n2
    
       n1 = n2
       n2 = nth
       count += 1
output:
Fibonacci

c. Tower of Hanoi
def TowerOfHanoi(n , source, destination, auxilliary): 
    if n==1: 
        print("Move disk 1 from source",source,"to destination",destination) 
        return
    TowerOfHanoi(n-1, source, auxilliary, destination) 
    print ("Move disk",n,"from source",source,"to destination",destination)
    TowerOfHanoi(n-1, auxilliary, destination, source) 
          

n = 4
TowerOfHanoi(n,'A','B','C')  

output:
Tower of Hanoi





Post a Comment

0 Comments