CJCoding With Joseph
15free / daySign inCreate account

Towers Of Hanoi

Write hanoi(n: int, source: str, target: str, spare: str) -> None that prints every move needed to transfer a tower of n disks from the source peg to the target peg, one move per line in the form Move disk 1 from A to C, where disk 1 is the smallest and only a smaller disk may sit on a larger one. The recursive plan: when n is 0 there is nothing to do; otherwise move the n - 1 smaller disks from source to spare (using target as the spare for that call), print the move of disk n from source to target, then move the n - 1 disks from spare to target (using source as the spare). Do NOT write a main block or any top-level test code; the tests construct the calls with pegs A (source), C (target) and B (spare). Input: one integer n, no prompt, which the tests read and pass to your function.

Expected Output:

Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C

= newline. The output ends with a newline — print one after the last line.

Hints4 available
Topics:
Recursion
📥 Auto-Input:
2\n
This input is automatically fed to your program's stdin
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Ctrl+Space to expand shortcuts (pr, inp, def)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.