Created
December 28, 2014 00:34
-
-
Save vnprc/e0016ba3674c8bbe7179 to your computer and use it in GitHub Desktop.
This is a programming exercise to solve the towers of hanoi puzzle. The physical puzzle has three pegs in a row. On the first peg is a stack of disks of descending diameter. You are only allowed to put a smaller disk on top of a larger disk, never the reverse. The task is to move the entire pile from the far left peg, to the far right peg. This …
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| This is a programming exercise to solve the towers of hanoi puzzle. | |
| The physical puzzle has three pegs in a row. On the first peg is a | |
| stack of disks of descending diameter. You are only allowed to put | |
| a smaller disk on top of a larger disk, never the reverse. The task | |
| is to move the entire pile from the far left peg, to the far right | |
| peg. | |
| This script accepts one input argument, n, for the number of disks. | |
| """ | |
| import sys | |
| stack1 = range(int(sys.argv[1]),0,-1) | |
| stack2 = [] | |
| stack3 = [] | |
| def move_stack(source_stack, source_position, dest_stack, transit_stack): | |
| if len(source_stack) > source_position + 1: | |
| move_stack(source_stack, source_position + 1, transit_stack, dest_stack) | |
| element = source_stack.pop() | |
| dest_stack.append(element) | |
| print_status() | |
| if element == 1: | |
| return | |
| move_stack(transit_stack, transit_stack.index(element - 1), dest_stack, source_stack) | |
| def print_status(): | |
| print str(stack1) | |
| print str(stack2) | |
| print str(stack3) + "\n" | |
| print_status() | |
| move_stack(stack1, 0, stack3, stack2) | |
| print "Done!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment