Recursively solving the Tower of Hanoi puzzle in Python

PHOTO EMBED

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:
            target.append(source.pop())
        # move tower of size n-1 from helper to target
        hanoi(n - 1, helper, source, target)
        
source = [4,3,2,1]
target = []
helper = []
hanoi(len(source),source,helper,target)

print source, helper, target
    
Result:
    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
content_copyCOPY

https://www.python-course.eu/towers_of_hanoi.php