在递归调用中更改变量被认为是突变

Is changing a variable in a recursive call considered mutation

我的目标是在不使用突变的情况下对列表求和。

def noMutObj(lst,pointer=0, result=0):
    if pointer == len(lst): 
        return result
    newResult = result + lst[pointer]
    return noMutObj(lst, pointer+1, newResult) 

我们是否会考虑 pointer 在我们进入递归阶段时进行变异, 突变是否仅适用于迭代循环中变化的变量?

您没有改变 pointer:您在每次调用 noMutObj 时传递了一个 不同的 值。每个堆栈帧都有自己的 pointer,其中 none 已更改。即使那样,您也只会更改本地副本。

如果你做了诸如

之类的事情,你就会发生突变
lst.append(newResult)
return noMutObj(lst, pointer+1, newResult)

通话前。相反,将更改后的列表发送到下一个调用的正确方法是

return noMutObj(lst[:].append(newResult), pointer+1, newResult)

... 创建一个新列表,附加 newResult 并将该临时对象传递到下一个级别。

我知道这根本不是您希望函数执行的操作;我只是在说明句法和语义原则。

更新

啊...现在我们有了目的...

突变:

def noMutObj(lst):
    if len(lst) == 0: 
        return 0
    return lst.pop() + noMutObj(lst)

无突变:

def noMutObj(lst):
    if len(lst) == 0: 
        return 0
    return lst[0] + noMutObj(lst[1:])