用python写出汉诺塔的过程记录
时间: 2024-02-28 07:37:49 浏览: 16
好的,下面是用 Python 写汉诺塔过程记录的代码:
def hanoi(n, A, B, C):
if n == 1:
print(f"move {n} from {A} to {C}")
else:
hanoi(n-1, A, C, B)
print(f"move {n} from {A} to {C}")
hanoi(n-1, B, A, C)
# 调用函数
hanoi(3, 'A', 'B', 'C')
输出结果为:
move 1 from A to C
move 2 from A to B
move 1 from C to B
move 3 from A to C
move 1 from B to A
move 2 from B to C
move 1 from A to C
相关问题
用python写个汉诺塔
下面是用 Python 实现汉诺塔的代码:
```python
def hanoi(n, source, target, auxiliary):
if n > 0:
# 将 n-1 个盘子从源柱移动到辅助柱
hanoi(n-1, source, auxiliary, target)
# 将第 n 个盘子从源柱移动到目标柱
print("Move disk", n, "from", source, "to", target)
# 将 n-1 个盘子从辅助柱移动到目标柱
hanoi(n-1, auxiliary, target, source)
# 测试
hanoi(3, 'A', 'C', 'B')
```
输出结果:
```
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
```
用python写个汉诺塔吧
当然可以!下面是一个使用 Python 编写的汉诺塔解决方案:
```python
def hanoi(n, source, target, auxiliary):
if n > 0:
# 将 n-1 个盘子从源柱移动到辅助柱
hanoi(n-1, source, auxiliary, target)
# 将第 n 个盘子从源柱移动到目标柱
print(f"Move disk {n} from {source} to {target}")
# 将 n-1 个盘子从辅助柱移动到目标柱
hanoi(n-1, auxiliary, target, source)
# 测试代码
num_disks = 3
hanoi(num_disks, 'A', 'C', 'B')
```
这段代码会打印出移动每个盘子的步骤。你可以修改 `num_disks` 变量来指定盘子的数量,以及修改 `'A'`, `'C'`, `'B'` 来指定起始柱、目标柱和辅助柱的名称。希望能帮到你!如果有其他问题,请随时提问。