【问题标题】:Return behaviour in recursive function递归函数中的返回行为
【发布时间】:2021-10-17 03:34:08
【问题描述】:

我无法完全理解以下递归函数中 return 语句的行为。在ifelse 语句中都有返回值,我得到了根据需要返回的int 值,但是删除任何一个函数都会返回None

我预计只需要在 else 中使用 return 语句,因为通过 if 语句运行的任何迭代都会递归地启动计算函数,直到它绕过 if

def solution(n, b):
    results = {}
    j = 0
    k = len(str(n))
    return calculate(n, b, j, k, results)


def calculate(n, b, j, k, results):
    i = ''
    x = ''.join(sorted([i for i in str(n)])[::-1])
    y = x[::-1]
    z = int(x, b) - int(y, b)
    while z:
        i = int(str(z % b) + str(i))
        z = z // b
    i = '0'*(k-len(str(i))) + str(i)
    if i not in results.values():
        results[j] = i
        j += 1
        s = calculate(i, b, j, k, results)
        return s #commenting this line causes code to return None
    else: #commenting else statement causes code to return None
        return len(results.keys()) - list(results.keys())[list(results.values()).index(i)]


print(solution('210022', 3))

【问题讨论】:

  • 除了注释掉else 语句,你需要减少它的返回缩进

标签: python python-3.x recursion return


【解决方案1】:

所有结束执行的函数,无论是递归的还是其他的,都会返回一个值,如果return 语句没有提供显式值,则默认情况下将None 传递给它的调用者。

以这个示例函数为例:

>>> def test(x):
        if x:
            s="if case"
        else:
            return "else case"

    
>>> print(test(True))
None
>>> print(test(False))
else case
>>> 

在第一种情况下,您输入“if case”执行那里的所有代码块,因为没有返回语句,您离开 if-else 代码块并继续下一个但在这种情况下有没有更多的代码可以运行,所以函数结束它的执行,默认返回 None。

在第二种情况下,您输入“else case”,但在这里您会找到一个return 语句,它告诉函数此时结束其执行并将该值传递给它的调用者。

你需要明确你想要从函数中得到什么值,仅仅因为函数最终调用自己并不意味着函数会神奇地知道这是一个递归函数(那只是一个编程技术)或两个,您希望从代码中某处某个函数调用链中某处某个 if-else 块的另一个分支获得结果。

递归调用的处理方式与调用任何其他函数没有什么不同,只是该函数正在调用自身,所以如果你对函数内部的某个函数调用得到的结果不做任何事情,你自然不会得到任何结果其中

这是第二个使用阶乘函数的例子

>>> def fact_bad(n,r=1):
        if n<=1:
            return r
        else:
            ans=fact_bad(n-1,n*r)

        
>>> def fact_good(n,r=1):
        if n<=1:
            return r
        else:
            ans=fact_good(n-1,n*r)
            return ans

    
>>> fact_bad(5) #you get nothing here because you do nothing with your recursive call inside
>>> fact_good(5) #you get your result as desire because because you do something with your recursive call inside, in this case that is just returning it
120
>>> 

【讨论】:

  • 感谢这篇文章。您的简化示例帮助我单击每个递归函数调用都需要“返回”并完成调用它的“if”语句,每个“返回”都会从最深的函数调用中带来最终的 else 语句“返回”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 2022-11-14
  • 2017-10-29
相关资源
最近更新 更多