Python3递归,避免变量更改以在不同的递归调用中全局反射(reflect)

标签 python python-3.x recursion

当在python3中使用递归时,假设我有一个函数'f(a,b)'。('b'是列表)并且在'f'内我我递归地调用“f”几次。如果“f”的子实例对列表“b”进行了一些更改,如何避免“b”中的这些更改反射(reflect)在调用父级 f 中? (我不会返回“b”)。 例如看看我下面的代码。在第二个 elif 中,我对函数 goToDepth 进行了两次递归调用。如果被调用的实例之一对 depthArr 进行更改,则该更改也会反射(reflect)在调用函数的 depthArr 副本中,这是我不希望的。如何避免这种情况? 预先非常感谢!

def goToDepth(headNode,depthArr):
    if(headNode==None):
        return
    elif(not depthArr):
        return
    elif(depthArr[-1]!=1):
        depthArr[-1]=depthArr[-1]-1
        goToDepth(headNode.left,depthArr)
        goToDepth(headNode.right,depthArr)
    elif (depthArr[-1]==1):    
        headNode.left,headNode.right=headNode.right,headNode.left
        depthArr.pop()
        goToDepth(headNode.left,depthArr)
        goToDepth(headNode.right,depthArr)
    else:
        return

最佳答案

尝试传递列表的副本:a[:] 创建浅拷贝。

使用copy模块创建深拷贝(但这可能是糟糕的设计)。

关于Python3递归,避免变量更改以在不同的递归调用中全局反射(reflect),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42577735/

相关文章:

python - 字符串中的"\n"无法正常工作

python - 随机数生成 python 3.x 默认库

list - 如何使这些简单的函数在 f# 中尾递归

javascript - 等待递归函数时获取未定义的结果

python - 数据框列表对应元素的平均值

python - Docker 在卷中运行应用程序

python - Tkinter/ttk - TreeView 不占据全帧

python-3.x - 标签未显示在python igraph中

python - 从类方法中提取重复代码

python - 我正在使用显示错误 : "maximum recursion depth exceeded in cmp" 的 Sphinx 文档工具