【问题标题】:how to answer this recursion question and is there a big difference between it and loop如何回答这个递归问题,它和循环之间有很大区别吗
【发布时间】:2019-06-11 17:30:50
【问题描述】:

下面的递归会打印出什么样的数字序列 如果我们以 N 为值 1 启动它?

       procedure Exercise (N)
        print the value of N;
           if (N < 3) then (apply the procedure Exercise to the
          value N + 1);
        print the value of N.

正确答案假设是 123321,但我尝试自己回答,我得到了 1233

【问题讨论】:

  • 你忘记了第二个“打印N的值”。
  • 如果您编写代码并执行算法,您可以轻松检查这一点。

标签: algorithm loops recursion


【解决方案1】:

当我想知道算法的作用时,我经常编写代码并执行它。 插入print 语句以跟踪执行和数据流有助于显示调用层次结构。

indent = ""

def exercise(n):
    global indent
    indent += "  "
    print(indent, "ENTER", n)

    # Original assignment, with assigned output not indented
    print("REAL", n)
    if n < 3:
        exercise(n+1)
    print("REAL", n)

    print(indent, "LEAVE", n)
    indent = indent[2:]

exercise(1)

输出:这是执行的跟踪,分配输出标记为“REAL”。函数 enter 和 exit 是交易和缩进的。

   ENTER 1
REAL 1
     ENTER 2
REAL 2
       ENTER 3
REAL 3
REAL 3
       LEAVE 3
REAL 2
     LEAVE 2
REAL 1
   LEAVE 1

是的,这可以通过一对循环轻松完成。这是否是“大不同”取决于您的判断功能。例如:

for i in range(1, n+1):
    print(n)
for i in range(n, 0, -1):
    print(n)

如果您对个别案例的处理是微不足道的(例如print(n)),那么这很容易。当您从一个元素到下一个元素的迭代是微不足道的(例如n+1)时,这很容易。但是,当其中任何一个都很复杂时,递归通常是描述和实现该过程的更容易处理的方式。

【讨论】:

    【解决方案2】:

    对于 N=1

    print 1;
    if(N<3) --> Exercise (1+1);  //the condition is TRUE here. So the function will be called again for N=2
    print 1;
    

    对于 N=2

    print 2;
    if(N<3) --> Exercise (2+1); // Condition is again TRUE. So the function is called for N=3 
    print 2;
    

    对于 N=3

    print 3;
    if(N<3) --> Exercise (3+1); // Condition is FALSE here. So the function won't be called
    print 3;
    

    结构会是这样的,

    print 1;
      print 2;
        print 3;
        print 3;
      print 2;
    print 1;
    

    【讨论】:

      【解决方案3】:

      你忘记了最后一个“打印N的值语句。

      假设我们使用Exercise(1) 调用它。那么这意味着它被评估为:

      Exercise(1):
          print 1
          Exercise(1+1)
          print 1
      

      这个Exercise(2) 调用,将导致:

      Exercise(2):
          print 2
          Exercise(2+1)
          print 2
      

      Exercise(3) 调用只会导致两个print 语句,因为if 语句中的条件为假,因此:

      Exercise(3):
          print 3
          print 3
      

      如果我们现在执行替换,我们得到:

      Exercise(1):
          print 1
              print 2
                  print 3
                  print 3
              print 2
          print 1
      

      这确实会产生预期的序列。

      【讨论】:

      • 我的问题是在替换过程中我不明白我的意思是最后的 3,2,1
      • 我们将Excerise(1+1)调用(第一个代码片段)替换为其主体(第二个代码片段),然后将Exercise(2+1)替换为其主体。
      猜你喜欢
      • 2014-12-02
      • 1970-01-01
      • 2016-01-27
      • 2011-03-06
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 2023-02-26
      • 1970-01-01
      相关资源
      最近更新 更多