# reads in 2 integers, prints their greatest common divisor # ECS 10, May 29, 2009 # Matt Bishop # read in a number # parameters: none # returns: 2 values # 1st: the number, if read successfully # 0, on EOF # -1, if not EOF and not successful # 2nd: True, if list read successfully; False, if not def getnum(): # read the input # catch any problems and bail out at once try: # read in ... something (a number, supposedly) n = input("Enter the number of disks: ") # this causes a TypeError if not a number n += 0 except EOFError: # didn't enter anything return 0, False except (NameError, TypeError, SyntaxError): # entered something bogus print "Please enter a positive integer" return -1, False # need at least one disk, and it better be an integer if n < 1 or n != int(n): print "Please enter a positive integer" return -1, False # return the value read return n, True # solve the Tower of Hanoi # parameters: n, number of disks to move from fromtower to totower # fromtower, the name of the tower with the disks # totower, the name of the tower where the disks are to # be moved to # temptower, the name of the tower to be used to hold disks # temporarily # returns: nothing def hanoi(n, fromtower, totower, temptower): # base case: only one disk, so move it directly to totower if n == 1: print "Move disk from tower", fromtower, "to tower", totower # recursion here else: # move the top n-1 disks to the temporary tower hanoi(n-1, fromtower, temptower, totower) # move the leftover disk to the destination # note: for efficiency, we could just put a copy of the # base case here hanoi(1, fromtower, totower, temptower) # move the n-1 disks from the temporary tower to the destination hanoi(n-1, temptower, totower, fromtower) # this puts it all together def main(): # print out a description of the program print """ The Tower of Hanoi puzzle solver will move disks from tower A to tower C. Tower B is in the middle and is used as a temporary tower. """ # get a positive integer n, okay = getnum() # got it! if okay: # solve the problem hanoi(n, "A", "C", "B") main()