Python:递归方法回滚变化?

标签 python python-3.x list class recursion

所以我陷入了这样的困境(简化版本)

class Node:
    def __init__(self):
        self.left= None
        self.cost = 0

    def change(self):
        if self.left is not None:
            self.left.cost=self.cost+1
            self.left.change

data=[]
for i in range(10):
    data.append(Node())
    if i>0:
        data[i].left = data[i-1]

data[8].change()
print(data[2].cost) #0

我要data[2].cost已更改,但它会回滚。我可以让它在不跳过递归的情况下工作吗? (在完整版本中,我实际上保留了一个具有四个指针的二维节点数组,因此迭代很糟糕。)

最佳答案

当您调用 change 方法时,您忘记了 ()

def change(self):
    if self.left is not None:
        self.left.cost=self.cost+1
        self.left.change()

输出:

6

关于Python:递归方法回滚变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53303539/

相关文章:

python - 如何加速 numpy.all 和 numpy.nonzero()?

Python 3.6 Selenium 如何通过父节点的引用找到子节点(xPath)

Python - 计算二叉树的分支和

python - 比较大列表中的项目 - 查找长度相差 1 个字母的项目 - Python

python - 计算每行中缺失/NaN 的数量

python - 即使我在 python 中将变量声明为 float,也会发生舍入

c# - 什么是完成主题的最佳方式

python-3.x - 在python pandas中,如何使用where条件使用外连接?

python - 有条件地从列表中选择下一个元素

python - 从两个匹配列表中随机选择 [Python]