Last active
February 13, 2023 16:57
-
-
Save abecus/b021098d6e23a4b567dfc62f4a710fba to your computer and use it in GitHub Desktop.
A code for solving tower of hanoi puzzle
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 tower_of_hanoi(r1, r2, r3, n_pegs): | |
if n_pegs == 1: | |
yield r1, r3 | |
return | |
yield from tower_of_hanoi(r1=r1, r2=r3, r3=r2, n_pegs=n_pegs - 1) | |
yield from tower_of_hanoi(r1=r1, r2=r2, r3=r3, n_pegs=1) | |
yield from tower_of_hanoi(r1=r2, r2=r1, r3=r3, n_pegs=n_pegs - 1) | |
def prettifyGame(game): | |
return list("".join(reversed(pole)) for pole in game) | |
N = 3 | |
# 1 | | | |
# 2 | | | |
# 3 | | | |
game = [list(str(i) for i in reversed(range(1, N+1))), [], []] | |
for a, b in tower_of_hanoi(0, 1, 2, N): | |
print(prettifyGame(game)) | |
game[b].append(game[a].pop()) | |
print(prettifyGame(game)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment