Skip to content

Instantly share code, notes, and snippets.

@mos3abof
Created March 24, 2013 14:24
Show Gist options
  • Save mos3abof/5232156 to your computer and use it in GitHub Desktop.
Save mos3abof/5232156 to your computer and use it in GitHub Desktop.
Classic puzzle "Tower of Hanoi" recursive solution in python
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