书上汉诺塔用的递归,我可以看懂,
书上代码如下:
def moveTower(height,fromPole, toPole, withPole):
if height >= 1:
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)
def moveDisk(fp,tp):
print("moving disk from",fp,"to",tp)
moveTower(2,"A","B","C")
我的问题是:
我想把每个柱子都当作一个stack,设置为s1,s2,s3, 我这个代码总是报错,这个思路哪里错了呢?把柱子当作stack如何用递归解决汉诺塔呢?
代码如下:
def hanoi(height,s1,s2,s3):
if height >= 1:
hanoi(height-1,s1[1:],s3,s2)
s3.append(s1.pop())
hanoi(height-1,s2[1:0],s3,s1)
总是报错:
```python
Traceback (most recent call last):
File "/Users/xiaoleiwang/Library/Mobile Documents/com~apple~CloudDocs/Desktop/CS/PekingDatastructure/practice/hanoi.py", line 15, in <module>
print(hanoi(2,s1,s2,s3))
File "/Users/xiaoleiwang/Library/Mobile Documents/com~apple~CloudDocs/Desktop/CS/PekingDatastructure/practice/hanoi.py", line 8, in hanoi
hanoi(height-1,s2[1:0],s3,s1)
File "/Users/xiaoleiwang/Library/Mobile Documents/com~apple~CloudDocs/Desktop/CS/PekingDatastructure/practice/hanoi.py", line 7, in hanoi
s3.append(s1.pop())
IndexError: pop from empty list
```