首页 > 解决方案 > 为什么我的回避功能甚至可以工作?语法混乱

问题描述

我编写了两个递归函数,它们的工作方式几乎相同。我试图让递归正确,然后我不小心偶然发现了答案,但语法让我感到困惑:

def fac(N):

    """
    Factorial of N.
    """
    ################# This makes no goddamn sense to me #################
    if N == 1:
        return N
    ####### because N == 1, yet 'return N' is the correct result ########
    elif N == 0:
        return 1

    return N*fac(N-1)

N == 1 如何作为退出条件为真,但也存储 fac(N) 的结果?与一个函数相同prod(),它与sum().

def prod(List):

    """
    Product of all numbers in a list.
    """

    if len(List) == 1:
        return List[-1]

    return List[-1]*prod(List[:-1])

我不明白最终结果是如何存储在List[-1]. python解释器是否return arg*func(arg)以特殊方式理解?

标签: pythonpython-3.xrecursion

解决方案


考虑计算 所需的循环fac(4)

1: fac(4) -> 4 * fac(3)  # It then has to calculate fac(3)
2: fac(3) -> 3 * fac(2)  # It then has to calculate fac(2)
3: fac(2) -> 2 * fac(1)  # It then has to calculate fac(1)

4: fac(1) -> 1  # Finally we've returned a value - now back up through the loops

3: fac(2) -> 2 * fac(1) == 2 * 1 == 2
2: fac(3) -> 3 * fac(2) == 3 * 2 == 6
1: fac(4) -> 4 * fac(3) == 4 * 6 == 24

第二部分实际上是同样的事情——向下递归直到你得到一个值,然后一直插入到你原来的请求。


推荐阅读