Towers of Hanoi explained in python

Sunday, July 1, 2012

This code illustrates the Towers of Hanoi problem solution with it's simple logic - to move 'n' number of discs from source(A) to destination(B) using an intermediate rod (B), recursively move n-1 discs from A to B, move nth disc from A to C and then move the rest n-1 discs from B to C, can't get any simpler than python.

Listing 1:

    Recursive solution for the towers of hanoi problem
    Author: S.Prasanna

import sys


def move(n, src, middle, dst):
    global TOTAL_MOVES
    if n == 0:
        move(n - 1, src, dst, middle)
        print "Move disk from %s to %s" % (src, dst)
        TOTAL_MOVES += 1
        move(n - 1, middle, src, dst)

n = int(raw_input("Enter the number of disks (n):"))
if n <= 0:
    print "Number of disks should be > 0."
    move(n, "A", "B", "C")
    print "Total moves = %s" % TOTAL_MOVES
Syntax highlighter: Pygments

Sample Output:

Enter the number of disks (n):3
Move disk from A to C
Move disk from A to B
Move disk from C to B
Move disk from A to C
Move disk from B to A
Move disk from B to C
Move disk from A to C
Total moves = 7

No comments:

Copyright © 2016 Prasanna Seshadri,, All Rights Reserved.
No part of the content or this site may be reproduced without prior written permission of the author.