用python编写汉诺塔程序
时间: 2023-08-28 22:06:52 浏览: 101
好的,以下是用 Python 编写汉诺塔程序的示例代码:
```python
def hanoi(n, source, target, auxiliary):
# 当只剩下一个盘子时,直接将其从源柱移动到目标柱
if n == 1:
print("Move disk 1 from {} to {}".format(source, target))
return
# 将 n - 1 个盘子从源柱移动到辅助柱
hanoi(n-1, source, auxiliary, target)
# 将第 n 个盘子从源柱移动到目标柱
print("Move disk {} from {} to {}".format(n, source, 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
```
在示例代码中,`n` 表示盘子的数量,`source`、`target` 和 `auxiliary` 分别表示源柱、目标柱和辅助柱。在函数中,我们使用递归的方式将盘子从源柱移动到目标柱,具体实现方式请参考代码注释。
阅读全文