Created
March 24, 2013 14:24
-
-
Save mos3abof/5232156 to your computer and use it in GitHub Desktop.
Classic puzzle "Tower of Hanoi" recursive solution in python
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
def hanoi(n, fr, to, spare): | |
'''(int, str, str, str) | |
Solve the classic puzzle Tower of Hanoi | |
>>> hanoi(1, "Middle", "Left", "Right") | |
- Move top ring in 'Middle' tower to the 'Left' tower | |
''' | |
def print_move(fr, to): | |
print "- Move top ring in '{}' tower to the '{}' tower".format(fr, to) | |
if n == 1: | |
print_move(fr, to) | |
else: | |
hanoi(n-1, fr, spare, to) | |
hanoi(1, fr, to, spare) | |
hanoi(n-1, spare, to, fr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment