The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
In [1]:
def move(n, source, target, auxiliary):
if n > 1:
move(n - 1, source, auxiliary, target)
print("Move disk {0} from {1} to {2}".format(n, source, target))
move(n - 1, auxiliary, target, source)
elif n == 1:
print("Move disk {0} from {1} to {2}".format(n, source, target))
else:
raise ValueError("n < 1")
In [4]:
def number_moves(n):
if n < 1:
raise ValueError("n < 1")
else:
return 2 ** n - 1
In [2]:
move(3, 'A', 'B', 'C')
In [3]:
move(0, 'A', 'B', 'C')
In [5]:
move(4, 'A', 'B', 'C')
In [8]:
print("Number of moves for n=10 is", number_moves(10))