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

how do I convert following python code to recursion

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

(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

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

棘手的部分(在我看来)是根据您在 -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))