#!/usr/bin/python # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # Copyright (C) 2008 Vino Fernando Crescini # Towers of Hanoi import sys; import re; # hanoi(peg_init, peg_dest, peg_temp, n) def hanoi(a, b, c, n): if n > 0: # move n - 1 discs from peg_init to peg_temp using peg_dest as temp hanoi(a, c, b, n - 1) # move nth disc from peg_init to peg_dest print "move disc", n, "from peg", a, "to peg", b # move n - 1 discs from peg_temp to peg_dest using peg_init as temp hanoi(c, b, a, n - 1) peg_init = "init" peg_dest = "dest" peg_temp = "temp" if len(sys.argv) != 2 and len(sys.argv) != 5: print "usage: hanoi.pl [ ]" sys.exit(1) # is n a number? if re.compile("^[0-9]+$").match(sys.argv[1]) is None: print "first argument must be a positive integer" sys.exit(2) if len(sys.argv) == 5: peg_init = sys.argv[2] peg_dest = sys.argv[3] peg_temp = sys.argv[4] hanoi(peg_init, peg_dest, peg_temp, int(sys.argv[1])) sys.exit(0);