Simple Tower Of Hanoi Algorithm in Python


The objective of the Tower of Hanoi mathematical game or puzzle is to move the entire stack to another rod, the following simple rules should be obeyed:

  1. Only 1 disk can be moved at a time.
  2. In Each move you can take the upper disk from one of the stacks and place it on top of another stack.
  3. No disk can be placed on top of a smaller disk
tower of Hanoi algorithm in Python

Python Program for Tower of Hanoi :

# source rod A = [] # middle rod B = [] # target rod C = [] def showAll():    print(A, B, C, '_________________', sep = '\n'); def move(n, source, target, bridge): if n > 0: # move n - 1 disks from source to bridge, so they are out of the way move(n - 1, source, bridge, target) # move the nth disk from source to target target.append(source.pop()) # Display our progress showAll() # move the n - 1 disks that we left on bridge onto target move(n - 1, bridge, target, source) discs = int(input("Number of disks: ")) print(discs, '_________________', sep = '\n'); A = list(range(1, discs+1))[::-1] showAll() # initiate call from source A to target C with auxiliary B move(discs, A, C, B) print("Number of moves:" + str(2**discs - 1))

Similar Posts:


Struggling to Understand Algorithm and Flowchart? Try our Notes

Want to Test Your Knowledge on Algorithm and Flowchart?


Recommended Deals End in

Online Games
Play 2048 Game Online and Relax.
Play 2048 Game Online

Search Tags

    Tower of Hanoi Algorithm Python code

    Program for Tower of Hanoi pseudocode

    How to solve Tower of Hanoi Puzzle in Python