(A) Only one disk can be moved at a time.
(B) A disk is slid off the top of one rod onto the next rod.
(C) A disk can only be placed on top of a larger disk.
Write a program to move the disks from the first rod to the last using Stacks.
So classic, so recursive:P
from stack import *
rods = [stack(), stack(), stack()]
def Hanoi(n, rod_from, rod_to):
if n == 2:
Move(rod_from, 3 - (rod_from + rod_to))
Move(rod_from, rod_to)
Move(3 - (rod_from + rod_to), rod_to)
else:
Hanoi(n - 1, rod_from, 3 - (rod_from + rod_to))
Move(rod_from, rod_to)
Hanoi(n - 1, 3 - (rod_from + rod_to), rod_to)
def Move(rod_from, rod_to):
print "Move from", rod_from, "to", rod_to
rods[rod_to].push(rods[rod_from].pop())
# Test case
if __name__ == "__main__":
# range(1, 8)[::-1] gets a reverse list
# Sequence slicing [starting-at-index : but-less-than-index [ : step]].
# Start defaults to 0, end to len(sequence), step to 1
for i in range(1, 8)[::-1]:
rods[0].push(i)
Hanoi(7, 0, 2)
for i in range(0, 7):
print "rods[2].pop():", rods[2].pop()