🇩🇪 Deutsch

01 Feb 2024

Python und Hanoi - rekursiv und flott

Schnelles Hanoi-Beispiel in Python, Rekursiv.


Danke, Internet!


#!/usr/bin/python3

def move_tower(height, from_pole, to_pole, with_pole):
    if height >= 1:
        move_tower(height-1, from_pole, with_pole, to_pole)
        move_disk(from_pole, to_pole)
        move_tower(height-1, with_pole, to_pole, from_pole)

def move_disk(fp, tp):
    print("moving disk from", fp, "to", tp)

#move_tower(3, "A", "B", "C")
move_tower(4, "A", "B", "C"

Demo


moving disk from A to C
moving disk from A to B
moving disk from C to B
moving disk from A to C
moving disk from B to A
moving disk from B to C
moving disk from A to C
moving disk from A to B
moving disk from C to B
moving disk from C to A
moving disk from B to A
moving disk from C to B
moving disk from A to C
moving disk from A to B
moving disk from C to B