【问题标题】:I am trying to find out a couple of recursion problems in Python 3.*我试图找出 Python 3 中的几个递归问题。*
【发布时间】:2020-07-14 19:32:42
【问题描述】:

我是 Python 的新手,我很难理解 return 语句在递归函数中的几种情况下是如何工作的。

第一个是:

为什么当n变为1时程序没有通过else测试返回时“返回10”乘以10? 也就是说这样的结果是:1200(或5*4*3*2*1*10)

def test(n):
    if n == 1:
        return 10
    else:
        return n * test(n-1)
print(test(5))

然后让我稍微改变一下,它的结果是 24,这意味着 10 被添加到下面的结果中。我想我只是对 return 的实际工作方式以及在具有多个 return 的递归中使用时的工作方式有疑问。

def test(n):
     if n == 1:
         return 10
     else:
         return n+test(n-1)

print(test(5))

任何帮助将不胜感激。

【问题讨论】:

  • 与其花时间写这个问题,不如先花时间学习递归的基础知识。
  • 另外,Stack Overflow 不是代码解释网站。你应该阅读How to Ask 部分
  • 谢谢。我确实理解递归,因为它只是一个调用自身的函数。我不明白的是返回最终答案的确切计算顺序,因为我忽略了它。我为问题的格式道歉。我是您网站的新手,当我阅读它时,我未能掌握所有细微差别。毕竟我老了,退休了,只是在寻找答案。对不起。

标签: python-3.x recursion return


【解决方案1】:

为什么当n变为1时程序没有通过else测试返回时“return 10”乘以10?

因为n * test(n-1)。当 n 变为 1 时,您返回 10 并且递归结束。所以n * test(1) 就像n * 10。第二种情况相同(但使用+)。

递归是多次调用同一个函数。使用不同的功能更容易理解。您返回一个数字并停止再次返回该函数以防止无限运行代码(您将得到一个堆栈溢出)。

def test1(n):
    if n == 1:                #n is 3 not 1
        return 10             #skipping
    else:                     #what to do then
        return n * test2(n-1) #return n times a value of another function, calling test2

def test2(n):
    if n == 1:                #n is 2 not 1
        return 10             #skipping
    else:                     #what to do then
        return n * test3(n-1) #return n times a value of another function, calling test3

def test3(n):
    if n == 1:                #n is 1
        return 10             #returning 10
    else:                     #never called
        return n * test4...(n-1)

打印(test1(3))

test3 test3(n-1) 变为10test2(n-1) 变为 n * test3(n-1) 所以 n * 10,在这种情况下为 2 * 10。而test1(n-1) 变为n * test2(n-1) 所以n * n * 10,在这种情况下为1 * 2 * 10

您看到 test1、test2 和 test3 是相同的函数,因此您可以直接调用相同的函数而无需创建另一个函数。

【讨论】:

  • 非常感谢。这更好地解释了它,因为必须首先评估 test3 才能得到 test2 的答案。我认为这就是我的问题发生的地方。这只是我的疏忽。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-21
  • 2011-01-15
  • 2022-07-04
相关资源
最近更新 更多