Skip to content

Instantly share code, notes, and snippets.

@Ivanca
Created March 2, 2018 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ivanca/bd5d5b88454b83402999b57e5ec4e8bf to your computer and use it in GitHub Desktop.
Save Ivanca/bd5d5b88454b83402999b57e5ec4e8bf to your computer and use it in GitHub Desktop.
def hanoi(n, source, helper, target):
print "hanoi( ", n, source, helper, target, " called"
if n > 0:
# move tower of size n - 1 to helper:
hanoi(n - 1, source, target, helper)
# move disk from source peg to target peg
if source[0]:
disk = source[0].pop()
print "moving " + str(disk) + " from " + source[1] + " to " + target[1]
target[0].append(disk)
# move tower of size n-1 from helper to target
hanoi(n - 1, helper, source, target)
source = ([4,3,2,1], "source")
target = ([], "target")
helper = ([], "helper")
hanoi(len(source[0]),source,helper,target)
print source, helper, target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment