我是完全新的蟒蛇,我目前正在通过关于河内和递归塔教程。我想,我递归,直到他们给这个例子中明白了:
i'm completely new to python and I am currently going over a tutorial about the towers of Hanoi and recursion. I thought that I understood recursion until they gave this example:
def moveTower(height,fromPole, toPole, withPole):
if height >= 1:
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)
#print(withPole)
def moveDisk(fp,tp):
print("moving disk from",fp,"to",tp)
moveTower(3,"A","B","C")
打印出正确的移动解决河内问题的塔与3盘: 从A盘移动到B 移动硬盘从A至C 移动磁盘从B到C 从A盘移动到B 移动硬盘从C到A 从C盘移动到B 移动硬盘从A到B
which prints the correct moves for solving the towers of hanoi problem with 3 discs: moving disk from A to B moving disk from A to C moving disk from B to C moving disk from A to B moving disk from C to A moving disk from C to B moving disk from A to B
我的问题是,它是如何做到这一点!?可能有人走过去的code中的线,让我明白它是如何打印正确的举动?我主要困惑着如何FP和TP的价值可以从改变到B到C.很抱歉,如果这是一个广泛的问题,一点!任何帮助将大大AP preciated!
my question is, how does it do so!? could someone go over the lines of code so that I understand how it prints the correct moves? i'm mainly confused with how the value of fp and tp can change from A to B to C. Sorry if this is bit of a broad question! Any help would be greatly appreciated!
在这个简单的情况下,你可以想像使用适当的打印
S,这样会发生什么:
In this simple case you can just visualize what happens by using appropriate print
s, like this:
def moveTower(height,fromPole, toPole, withPole):
if height >= 1:
print( " "*(3-height), "moveTower:", height, fromPole, toPole )
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole,height)
moveTower(height-1,withPole,toPole,fromPole)
#print(withPole)
def moveDisk(fp,tp,height):
print(" "*(4-height), "moving disk", "~"*(height), "from",fp,"to",tp)
moveTower(3,"A","B","C")
的输出是:
moveTower: 3 A B
moveTower: 2 A C
moveTower: 1 A B
moving disk ~ from A to B
moving disk ~~ from A to C
moveTower: 1 B C
moving disk ~ from B to C
moving disk ~~~ from A to B
moveTower: 2 C B
moveTower: 1 C A
moving disk ~ from C to A
moving disk ~~ from C to B
moveTower: 1 A B
moving disk ~ from A to B
上一篇:怎么算单或双引号双引号
下一篇:填充在SHA256消息消息