parameterized iterator?
Fortepianissimo
fortepianissimo at yahoo.com.tw
Tue Feb 18 21:00:11 EST 2003
Just occurs to me that if I can somehow pass in an argument to specify
a special ordering when traversing a tree, that'll be perfect. A
simplified tree node iterator is something like this:
class Node:
def __iter__ (self): return self.postorder()
def postorder (self):
if hasattr(self,daughters):
for d in daughters:
for dd in d: yield dd
yield self
daughters is a list of the daughter nodes. This allows me to traverse
the tree in postorder:
for node in root:
<do something to node>
Now I want to be able to slip in a new traversal generator to define
my own way of traversal. The only way I can think of is
def postorder (node):
...
def preorder (node):
...
tFunc=preorder # change this if necessary
class Node:
def __iter__ (self): return tFunc(self)
But then again 'tFunc' is immutable and if I change tFunc to another
traversal generator nothing would change! Unless I make tFunc a list
(mutable):
tFunc=[preorder]
and change and call tFunc[0] instead of tFunc. This is rather ugly. Is
there any better way to do this?
Thanks!
More information about the Python-list
mailing list