【问题标题】:Calculating the recursive "n" number计算递归“n”数
【发布时间】:2022-01-09 17:50:02
【问题描述】:

我现在正在使用练习本自学 python 2。我目前正在研究递归函数。我有点困惑如何计算“n”值。下面是我为自己创建的一个简单示例。

def input(x, y, n):  
    if n == 0:
        return
    print (x + y), "Recurse no.", n
    input(x, y, n - 1)

    print (x + 1), "Recurse no.", n
    input(x, y, n - 1)

input(10, 6, 3)
Result Recurse number
16 Recurse no. 3
16 Recurse no. 2
16 Recurse no. 1
11 Recurse no. 1
11 Recurse no. 2
16 Recurse no. 1
11 Recurse no. 1
11 Recurse no. 3
16 Recurse no. 2
16 Recurse no. 1
11 Recurse no. 1
11 Recurse no. 2
16 Recurse no. 1
11 Recurse no. 1

我尝试如下手动计算“n”,但不确定在前 3 行之后它是如何工作的。

manual working

如果有人能解释在 n = 3 2 1 之后是如何计算出来的,我将不胜感激。

【问题讨论】:

  • 请正确格式化您的代码
  • 我相信您没有正确复制粘贴您的代码?现在它没有多大意义。
  • 请问你为什么要学 Python2 而不是 Python3?
  • 缩进在 Python 中非常重要。您的代码没有正确缩进。
  • 您是否知道 Python 2 已经死了(不支持)2 年了,而且这在 10 多年前就已经宣布了?

标签: python recursion python-2.x


【解决方案1】:

我对你的函数做了一个小改动,以便更容易地看到发生了什么

def input(x, y, n):
    if n == 0:
        return
    print (x + y, "A Recurse no.", n)
    input(x, y, n - 1)

    print (x + 1, "B Recurse no.", n)
    input(x, y, n - 1)

input(10, 6, 3)

输出:

16 A Recurse no. 3
16 A Recurse no. 2
16 A Recurse no. 1
11 B Recurse no. 1
11 B Recurse no. 2
16 A Recurse no. 1
11 B Recurse no. 1
11 B Recurse no. 3
16 A Recurse no. 2
16 A Recurse no. 1
11 B Recurse no. 1
11 B Recurse no. 2
16 A Recurse no. 1
11 B Recurse no. 1

因此,在 3,2,1 之后,您的输入会使用 input(10,6,0) 调用,因此它会在不打印任何内容的情况下返回,并且可以执行第二部分。

【讨论】:

    【解决方案2】:

    您可以看到左侧部分以查看递归调用堆栈。 输入函数被调用了 4 次。 而当函数完成函数返回或者遇到return 0语句时,函数从调用栈中移除。

    所以关于你的问题。您使用的变量与函数本身一起存储在堆栈中。

    在下面的示例中,如果我单击第一个函数调用,我将看到 n=3。 如果我点击第二个,我会看到 n=2,等等。

    【讨论】:

      猜你喜欢
      • 2020-07-30
      • 2014-05-02
      • 2015-08-29
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-03
      • 2022-11-23
      相关资源
      最近更新 更多