Tuesday, May 5, 2015

Tower of Hanoi - Python

Today i will show a little example in Python of the famous problem Tower of Hanoi.

"The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
  1. Only one disk can be moved at a time.
  2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
  3. No disk may be placed on top of a smaller disk.
With three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2n - 1, where n is the number of disks." 

See the example below:


If you want to know more about Tower of Hanoi click here

Ok, ok, but where's the code?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def Hanoi(pin0, pin2, pin1, num):
  if num == 1:
    print 'Move from ' + str(pin0) + ' to ' + str(pin2)
  else:
    Hanoi(pin0, pin1, pin2, num-1)
    Hanoi(pin0, pin2, pin1, 1)
    Hanoi(pin1, pin2, pin0, num-1)

# Parameters: (from)Pin0, (to)Pin2, (helper)Pin1, Number of Disks
Hanoi(0, 2, 1, 3)

The code shows each necessary move to pass all the disks from the first rod to the last rod.

If you liked please share. If you have any questions just ask.

No comments:

Post a Comment