i don’t get the full grasp on python iterators,
i got an object with a list of children, and i want to iterate through this structure.
I want to get the same behaviour as with the printall function but with an iterator.
class t:
def __init__(self, i):
self.l = []
self.a = 0
for ii in range(i):
self.a = ii
self.l.append(t(i-1))
def __iter__(self):
return self
def next(self):
for i in self.l:
yield i.__iter__()
yield self
def printall(self):
for i in self.l:
i.printall()
print self.a
hope thats enough information, thanks
edit:
i just want to be able to iterate through all the leafs of the tree and do something with the object, i.e. when i have an instance
bla = t(3)
i want to be able to go through every node with
for x in bla:
print x.a
for example. i want to be able to something with each x,
i just have to access every child once
It sounds like you want the iterator to act as a tree traversal. Study the
itertoolsmodule and you can really go places.EDIT: Below is the originally accepted implementation. It has a performance problem; I would remove it, but it seems wrong to remove content that was an accepted answer. It will fully traverse the entire structure, creating
O(N*log[M](N))generator objects (for a balanced tree with branching factorMcontainingNtotal elements), before yielding any values. But it does produce the desired result with a simple expression.(The above implementation visits areas of the tree on demand and has only
O(M+log[M](N))generator objects in memory at a time. In both implementations, onlyO(log[M](N))levels of nested generators are expected.)