Last active
December 18, 2015 22:28
-
-
Save thisiswei/5854425 to your computer and use it in GitHub Desktop.
I feel I just got smarter
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
""" | |
The Towers of Hanoi is a puzzle where there is a pyramid of disks, each one | |
smaller than the one below it, all placed on to one of three rods. The puzzle | |
is to move all the disks from the left rod to the right rod, possibly using the | |
middle rod as necessary. You can only move one disk at a time, onto another | |
rod, but never moving a disk onto a disk that is smaller. Return a list of the | |
moves in the form[1, 'L', 'M'], which means to move disk number 1, the smallest | |
disk, from the left to the middle rod. | |
hanoi(2) → [[1, 'L', 'M'], [2, 'L', 'R'], [1, 'M', 'R']] | |
hanoi(1) → [[1, 'L', 'R']] | |
hanoi(0) → [] | |
""" | |
#wtf! I figure this out! damn | |
def hanoi(n, start='L', end='R', using='M'): | |
if n <= 0: | |
return [] | |
return (hanoi(n-1, start, using, end) + | |
[[n, start, end]] + | |
hanoi(n-1, using, end, start)) | |
""" | |
Hint: You can break this down into pieces: to move a pile of n disks from rod L | |
to rod R, first move n-1 of them (all but the bottom disk) out of the way: to | |
rod M. Then move the bottom disk to rod R -- it will be clear because | |
everything is out of the way. Then, move the the pile of n-1 from M to B. Now, | |
how do you move the pile of n-1? The same way you moved the pile of n! It is | |
guaranteed to work, because whether you are moving n, n-1, n-2 or whatever, | |
they are all the smallest disks, and thus it doesn't matter where the other | |
disks are.""" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment