# Solves the Tower of Hanoi puzzle.
# Written by Eric Martin for COMP9021

# Move a tower of n disks on the start-peg to the finish-peg,
# using the spare-peg as an intermediate.

def move_towers(n, start, finish, spare):
    if n == 1:
        print('Move a disk from peg {:} to peg {:}'.format(start, finish))
        move_towers(n - 1, start, spare, finish)
        print('Move a disk from peg {:} to peg {:}'.format(start, finish))
        move_towers(n - 1, spare, finish, start)

while True:
        n = int(input('Enter a positive integer: '))
        if n < 0:
            raise ValueException
        print('Incorrect input, try again.')
move_towers(n, 1, 3, 2);

Resource created Wednesday 02 September 2015, 11:06:18 AM.

file: hanoi.py

Back to top

COMP9021 15s2 (Principles of Programming) is powered by WebCMS3
CRICOS Provider No. 00098G