Recursively solving the Tower of Hanoi puzzle in Python


Wed Jan 01 2020 19:00:00 GMT+0000 (Coordinated Universal Time)

Saved by @hellointerview #python #puzzles #interesting

def hanoi(n, source, helper, target):
    if n > 0:
        # move tower of size n - 1 to helper:
        hanoi(n - 1, source, target, helper)
        # move disk from source peg to target peg
        if source:
        # move tower of size n-1 from helper to target
        hanoi(n - 1, helper, source, target)
source = [4,3,2,1]
target = []
helper = []

print source, helper, target
    Move disk 1 from A to B
    Move disk 2 from A to C
    Move disk 1 from B to C
    Move disk 3 from A to B
    Move disk 1 from C to A
    Move disk 2 from C to B
    Move disk 1 from A to B