python编写汉诺塔
时间: 2023-10-17 20:11:44 浏览: 100
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
```
阅读全文