正如其他人所建议的那样,这看起来像一棵树(或图)遍历。
您可能想查看递归算法。例如:
class A(object):
def __init__(self, x, child = None):
self.x = x
self.child = child
def increments(self):
self.x += 1 # increment this one
# Check that the child is not 'None' or some other value
if hasattr(self.child, 'increments'):
# recursively increment the child
self.child.increments()
def __repr__(self):
# friendly representation
return 'A(%r, %r)' % (self.x, self.child)
>>> a = A(1, A(2, A(3, A(4))))
>>> a
A(1, A(2, A(3, A(4, None))))
>>> a.increments()
>>> a
A(2, A(3, A(4, A(5, None))))
>>> a.increments()
>>> a
A(3, A(4, A(5, A(6, None))))
基本上,您将递归函数定义X
为:
- 对对象的内部状态做一些事情
- 处理任何
X
依赖对象(例如它的孩子(ren))
- 编辑 -
关于您仅更新最后一个值的最后评论(对于树,这称为叶子):您有两种解决方案:
一种是为所有图形使用相同类型的节点,并将叶子定义为“没有子节点的节点”:
class Node(object):
def __init__(self, x, *children):
self.x = x
self.children = []
if children:
self.children.extend(children)
def updateLeafs(self, newx):
if self.children:
# This node has children: it is not a Leaf
for c in self.children:
c.updateLeafs(newx)
else:
# This node has no children -> Definition of a leaf !
self.x = newx
def __str__(self):
"Pretty printing of the tree"
if self.children:
# A node
return 'Node(%s -> [%s])' % (repr(self.x), ','.join(str(c) for c in self.children))
else:
# A leaf
return 'Node(%s)' % repr(self.x)
你得到:
>>> tree = Node(1, Node(4, Node(4, Node(4), Node(5)), Node(6), Node(7, Node(8))))
>>> print tree
Node(1 -> [Node(4 -> [Node(4 -> [Node(4),Node(5)]),Node(6),Node(7 -> [Node(8)])])])
>>> tree.updateLeafs(10)
>>> print tree
Node(1 -> [Node(4 -> [Node(4 -> [Node(10),Node(10)]),Node(10),Node(7 -> [Node(10)])])])
另一种可能性是为您的叶子和树枝设置不同的类型:
class Branch(object):
def __init__(self, *children):
self.children = children
def update(self, newx):
for c in self.children:
c.update(newx)
def __str__(self):
"Pretty printing of the tree"
return 'Branch([%s])' % (','.join(str(c) for c in self.children))
class Leaf(object):
def __init__(self, x):
self.x = x
def update(self, newx):
self.x = newx
def __str__(self):
return 'Leaf(%s)' % self.x
这会产生:
>>> tree = Branch(Branch(Branch(Leaf(4), Leaf(5)), Leaf(6), Branch(Leaf(8))))
>>> print tree
Branch([Branch([Branch([Leaf(4),Leaf(5)]),Leaf(6),Branch([Leaf(8)])])])
>>> tree.update(10)
>>> print tree
Branch([Branch([Branch([Leaf(10),Leaf(10)]),Leaf(10),Branch([Leaf(10)])])])
前者允许动态叶子(即您可以稍后将新子节点添加到叶子,这使它们不再是叶子),而如果您的树节点和叶子本质上不同(例如,对于文件系统,您的叶子所在的位置),后者更有意义文件和树是一个目录结构)。这真的取决于你的问题来选择哪个是最好的。