Created
December 27, 2013 07:29
-
-
Save creamidea/8143716 to your computer and use it in GitHub Desktop.
汉诺塔算法
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
#!/usr/bin/env python | |
def move(origin, dest): | |
print "%s -> %s" % (origin, dest) | |
def hanoi(n, origin, assist, dest): | |
if n is 1: | |
move(origin, dest) | |
else: | |
hanoi(n - 1, 'A', 'C', 'B') | |
move(origin, dest) | |
hanoi(n - 1, 'B', 'A', 'C') | |
def hanoi2(n, **kwargs): | |
op = kwargs | |
if n is 1: | |
move(op["origin"], op["dest"]) | |
else: | |
hanoi2(n-1, origin='A', dest='B', assist='C') | |
move(op["origin"], op["dest"]) | |
hanoi2(n-1, origin='B', dest='C', assist='A') | |
if __name__ == '__main__': | |
print '*' * 20 | |
hanoi(3, 'A', 'B', 'C') | |
print '*' * 20 | |
hanoi2(3, origin='A', dest='C', assist='B') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reference:
Wiki:汉诺塔