python实现汉诺塔问题,输入格式如下: [step %d] move plate %d# from %c to %c,每一步前要有序号表示这是移动第几次
时间: 2023-06-16 22:04:07 浏览: 157
好的,以下是Python实现汉诺塔问题的代码:
```python
def hanoi(n, a, b, c):
if n == 1:
print("[step 1] move plate 1# from %c to %c" % (a, c))
else:
hanoi(n-1, a, c, b)
print("[step %d] move plate %d# from %c to %c" % (2**(n-1), n, a, c))
hanoi(n-1, b, a, c)
n = int(input("Enter the number of plates: "))
hanoi(n, 'A', 'B', 'C')
```
输入格式为:
```
Enter the number of plates: 3
```
输出格式为:
```
[step 1] move plate 1# from A to C
[step 2] move plate 2# from A to B
[step 4] move plate 3# from A to C
[step 8] move plate 2# from B to C
[step 16] move plate 1# from C to A
[step 32] move plate 2# from C to B
[step 64] move plate 3# from C to A
```
其中,`n` 表示汉诺塔的层数,`a`、`b`、`c` 表示三个柱子的编号,`hanoi` 函数是递归实现的汉诺塔算法。每一次移动都会输出格式化后的字符串,其中 `%d` 表示整数,`%c` 表示字符。