如何将以下 python 代码转换为递归

时间:2021-06-01 12:46:17

标签: python-3.x recursion sequence

我希望生成一个数字序列,以便我得到:

(n - 10)^2, (n - 9)^2, ... n^2, ... (n + 9)^2, (n + 10)^2

我有以下代码通过循环执行此操作:

def a_func(number):
start = -10
result = []
while start <= 10:
    result.append((number + start) ** 2)
    start += 1
return result

我将如何用递归来做同样的事情?

1 个答案:

答案 0 :(得分:1)

棘手的部分(在我看来)是根据 -10 到 10 之间的范围确定如何“开始”和“停止”。让我们看看如何使用闭包来做到这一点。

从概念上讲,我们将:

def func_a(n):
    ## ---------------
    ## Do "something" based on "n" and the current value of "i"
    ## ---------------
    def func_b(n,i):
        ## ---------------
        ## i is larger than our stopping point to stop
        ## ---------------
        if i > from_to[1]:
            return []
        ## ---------------

        ## ---------------
        ## i is within range so calculate "this" value
        ## and append all the additional values
        ## ---------------
        return [(n + i)**2] + func_b(n, i+1)
        ## ---------------
    ## ---------------

    ## ---------------
    ## This variable hidden inside the closure will allow
    ## us to specify where to start and stop our recursion
    ## ---------------
    from_to = (-10, 10)
    ## ---------------

    return func_b(n, from_to[0])

print(func_a(10))

现在让我们用 lambda 清理一下:

def func_a(n):
    from_to = (-10, 10)
    func_b = lambda n, i: [(n + i)**2] + func_b(n, i+1) if i <= from_to[1] else []
    return func_b(n, from_to[0])

print(func_a(10))

打印:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]

从技术上讲,如果您乐于对这些值进行硬编码,则不需要 from_to。在这种情况下,您可以简单地执行以下操作:

def func_a(n):
    func_b = lambda n, i: [(n + i)**2] + func_b(n, i+1) if i <= 10 else []
    return func_b(n, -10)

print(func_a(10))
相关问题