python编写汉诺塔程序
时间: 2023-11-20 13:54:54 浏览: 133
以下是Python实现汉诺塔问题的代码:
```python
def hanoi(n, a, b, c):
if n == 1:
print(a, '-->', c)
else:
hanoi(n-1, a, c, b)
print(a, '-->', c)
hanoi(n-1, b, a, c)
n = int(input('请输入汉诺塔的层数:'))
hanoi(n, 'A', 'B', 'C')
```
运行程序后,输入汉诺塔的层数,程序将会输出汉诺塔移动的步骤。
相关问题
用python编写汉诺塔程序
好的,以下是用 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` 分别表示源柱、目标柱和辅助柱。在函数中,我们使用递归的方式将盘子从源柱移动到目标柱,具体实现方式请参考代码注释。
python编写汉诺塔
以下是Python编写汉诺塔的代码:
```python
def hanoi(n, A, B, C):
if n == 1:
print('Move disk', n, 'from', A, 'to', C)
else:
hanoi(n-1, A, C, B)
print('Move disk', n, 'from', A, 'to', C)
hanoi(n-1, B, A, C)
n = int(input('Enter the number of disks: '))
hanoi(n, 'A', 'B', 'C')
```
运行代码后,程序会要求输入要移动的盘子数,然后按照汉诺塔的规则递归地输出每一步移动的过程。
例如,输入要移动3个盘子,输出如下:
```
Enter the number of disks: 3
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
```
阅读全文