1
2 def printMove (to, fr):
3 '''Prints the moves to be executed'''
4 print 'move from ' + str (fr) + ' to ' + str (to)
5
6 def towers (n, fr, to, sp):
7 if n == 1:
8
9 printMove (to, fr) #
10
11 else:
12 towers (n-1, fr, sp, to)
13
14
15
16 towers (1, fr, to, sp)
17 towers (n - 1, sp, to, fr)
18
19 towers (3, 'fr', 'to', 'sp')
请有人解释为什么此代码在第12行完成递归调用,n
递减为1,然后再次调用n = 2
,然后转到第16行?我一直在使用python导师,并试图了解每个步骤以及算法的工作原理。
答案 0 :(得分:4)
首先,你的代码并不完美。以下是为您更改的towers
功能 - >
def towers (n, fr, to, sp):
if n == 1:
printMove (to, fr)
else:
towers (n-1, fr, sp, to)
printMove (to,fr)
towers (n-1, sp, to, fr)
这里有解释。看图片 - >
通过拨打Movetower(3,a,b,c)
,您打算将所有3张光盘从塔A
移至塔B
。所以顺序调用是 - >
1. Movetower(3,a,b,c) // No Move needed
2. Movetower(2,a,c,b) // No move needed
3. Movetower(1,a,b,c) // Here is the time to move, move disc1 from a to b
4. Movetower(2,a,c,b) // Returning to this call again, this is the time to move disc2 from a to c
5. Movetower(1,b,c,a) // Again the time to move, this time disc1 from b to c
6. Movetower(3,a,b,c) // Returning to this call again, this is the time to move disc3 from a to b
7. Movetower(2,c,b,a) // Not the time to move
8. Movetower(1,c,a,b) // Here is the time to move, move disc1 from c to a
9. Movetower(2,c,b,a) // Returning to this call again, this is the time to move disc2 from c to b
10.Movetower(1,c,a,b) // Here is the time to move, move disc1 from a to b
希望有所帮助:)
您还可以在此处找到一些好的解释:Tower of Hanoi: Recursive Algorithm
对于动画:https://www.cs.cmu.edu/~cburch/survey/recurse/hanoiex.html
答案 1 :(得分:1)
First, an aside: the code you show contains an error on line 9, which is not indented legally.
Execution begins with line 19, which calls towers(3,...), which proceeds up to line 12, where it calls towers(2,...), which proceeds up to line 12, where it calls towers(1,...), which prints something and returns. When it returns, execution resumes in the towers(2,...) invocation, and resumes at line 16, as you observed.