Created
December 1, 2020 03:33
-
-
Save thanhnguyen2187/dea1ed2443c374cf2a8e27ccb2126e3f 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
| """ | |
| Write a recursive function that prints a solution to the classic Towers of | |
| Hanoi puzzle. Your function should accept three integer parameters representing | |
| the number of disks, the starting peg number, and ending peg number. Your | |
| function should print the solution to the game to move from the given start peg | |
| to the given end peg. For example, the call of `hanoi(3, 1, 3)` should print | |
| the folowing output to move the three pegs from peg #1 to peg #3. | |
| ``` | |
| move disk 1 from peg 1 to peg 3 | |
| move disk 2 from peg 1 to peg 2 | |
| move disk 1 from peg 3 to peg 2 | |
| move disk 3 from peg 1 to peg 3 | |
| move disk 1 from peg 2 to peg 1 | |
| move disk 2 from peg 2 to peg 3 | |
| move disk 1 from peg 1 to peg 3 | |
| ``` | |
| """ | |
| def hanoi( | |
| number_of_disks: int, | |
| starting_peg: int, | |
| ending_peg: int, | |
| ): | |
| pegs = set((1, 2, 3)) | |
| pegs.remove(starting_peg) | |
| pegs.remove(ending_peg) | |
| middle_peg = pegs.pop() | |
| if number_of_disks > 0: | |
| hanoi( | |
| number_of_disks=number_of_disks - 1, | |
| starting_peg=starting_peg, | |
| ending_peg=middle_peg, | |
| ) | |
| print( | |
| f"move disk {number_of_disks} " | |
| f"from peg {starting_peg} " | |
| f"to peg {ending_peg}." | |
| ) | |
| hanoi( | |
| number_of_disks=number_of_disks - 1, | |
| starting_peg=middle_peg, | |
| ending_peg=ending_peg, | |
| ) | |
| hanoi( | |
| number_of_disks=3, | |
| starting_peg=1, | |
| ending_peg=3, | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment