Python tower of Hanoi programming code

 

The Tower of Hanoi problem is a classic recursive problem. Here is a simple way to implement the Tower of Hanoi in Python:
```python
def hanoi(n, source, target, auxiliary):
if n > 0:
# move n-1 plates from source to auxiliary
hanoi(n- 1, source, auxiliary, target)

# Move nth plate from source to target
print(f"Move {n}th plate from {source} to {target}")

# Move n-1 plate from auxiliary Move to target
hanoi(n-1, auxiliary, target, source)
# Test
hanoi(3, "A", "C", "B") ``
`
This program defines a function called `hanoi` which Accepts four parameters: the number of plates (n), the source column (source), the target column (target), and the auxiliary column (auxiliary). By recursively calling the `hanoi` function, we can solve the Hanoi Tower problem. In the test, we use 3 plates, the source peg is A, the target peg is C, and the auxiliary peg is B.

The following is the code for implementing the Tower of Hanoi in Python:
```python
def hanoi(n, source, target, auxiliary):
if n > 0:
# Move n-1 plates from the source column to the auxiliary column
hanoi(n-1 , source, auxiliary, target)
# move the nth disk from the source column to the target column
print("Move disk", n, "from", source, "to", target)
# move n-1 disks from the auxiliary The column moves to the target column
hanoi(n-1, auxiliary, target, source)
# Test
hanoi(3, 'A', 'C', 'B')
```
The output result is:
```
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C

Supongo que te gusta

Origin blog.csdn.net/qq_42751978/article/details/130695135
Recomendado
Clasificación