【问题标题】:Towers of Hanoi recursive calls河内塔递归调用
【发布时间】: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


    【解决方案1】:

    首先,您的代码并不完全正常。这是为您更改的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

    【讨论】:

    • 感谢您的解释,我使用的代码来自 edx MIT 对使用 python 进行计算和编程的介绍。我试图在不逐字复制的情况下重新创建它,并意识到我无法获得正确的顺序并且不理解每个步骤。
    【解决方案2】:

    首先,顺便说一句:您显示的代码在第 9 行包含一个错误,该错误没有合法缩进。

    执行从第 19 行开始,调用 towers(3,...),继续到第 12 行,调用 towers(2,...),继续到第 12 行,调用 towers (1,...),它打印一些东西并返回。当它返回时,在 towers(2,...) 调用中继续执行,并在第 16 行继续执行,如您所见。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-28
      • 2012-09-11
      • 2013-09-28
      • 1970-01-01
      • 2017-02-04
      • 2016-01-27
      • 1970-01-01
      相关资源
      最近更新 更多