Programming (en)

The Tower of Hanoi in Python ?

# Tower of Hanoi (puzzle)
# invented by Édouard Lucas
# recursive solution in Python

def Hanoi (disks,sourcePeg, sparePeg, targetPeg):
    # disks > 0
    if disks:
        Hanoi (disks-1,sourcePeg,targetPeg,sparePeg)
        print ("I move disk", disks, "from",sourcePeg,"to",targetPeg)
        Hanoi (disks-1,sparePeg,sourcePeg,targetPeg)

# 4 disks on peg A to be moved to peg C
Hanoi (4,"peg A","peg B","peg C")
print ()
print ("DONE !")

# program: The Tower of Hanoi
# implementation in Python 3.x: A.-P. Gaspar
French mathematician Edouard Lucas, inventor of the Tower of Hanoi puzzle

Leave a Reply

, , ,

English - Programming (en)