Search Here

Python program to implement Tower of Hanoi

# Tower of Hanoi

import math
def moveTower(height, frompole, topole, withpole):
    global c
    if height >= 1:
        c = c + 1
        moveTower(height-1, frompole, withpole, topole)
        moveDisk(frompole, topole)
        moveTower(height-1, withpole, topole, frompole)

def moveDisk(fp,tp):
    print("\tMoving disk from",fp,"to",tp)
    

# __________________________ Main Block Starts __________________________
print("\t\t\t____Tower Of Hanoi____")
c = 0
n = int(input("\nEnter number of poles : "))
moveTower(n,"A","B","C")
print("\nTheoretical complexity: ",math.pow(2,n))
print("Tractical complexity: ",c)

Tower of Hanoi
Output

No comments:

Post a Comment