【发布时间】:2016-08-30 16:49:16
【问题描述】:
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 导师,并试图了解每个步骤以及该算法为何有效。
【问题讨论】:
标签: python algorithm recursion towers-of-hanoi