Last active
December 31, 2024 04:07
-
-
Save msyvr/82608a53b867524079e295c8e8ec9aa7 to your computer and use it in GitHub Desktop.
mit 6.0001 recursion - towers of hanoi
This file contains 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 towers_rec(n, home, destination, temp): | |
if n == 1: | |
moves.append((home+' to '+destination)) | |
else: | |
towers_rec(n-1, home, temp, destination) | |
towers_rec(1, home, destination, temp) | |
towers_rec(n-1, temp, destination, home) | |
if __name__ == "__main__": | |
print('Elements are stacked at position A, which is \'home\'.\n \ | |
Move them to position B, which is \'destination\'.\nImportant! \ | |
The home stack is ranked as:\nbottom biggest, top smallest...\n \ | |
and the destination stack must be ranked the same way.\nThere\'s \ | |
one spare position you can use called \'temp\' which starts at \ | |
position C.\nTwo rules:\n1. move one element at a time, and\n2. \ | |
never place an element on top of a smaller element.') | |
moves=[] | |
n = int(input('How many stacked rings?: ')) | |
towers_rec(n, 'A', 'B', 'C') | |
print(f'The winning set of moves: {moves}\nIt took (2^n)-1 = {len(moves)} moves!') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment