parameterized iterator?
Raymond Hettinger
vze4rx4y at verizon.net
Wed Feb 19 17:59:09 EST 2003
"Fortepianissimo" wrote
> 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.
Python's own solution to this problem is to use a different method
for each type of iterator:
mydict.itervalues()
mydict.iteritems()
mydict.iterkeys()
Alternatively, you can create a method with a parameter.
Don't use __iter__() for this since it is already defined with
no parameters; instead, try something like: traverse(ordering).
Using generators are a clean way to return an iterator whose next()
method obeys the ordering:
class Tree:
. . .
def traverse(order):
"Untested psuedocode approximation of what you want"
if order == INORDER:
self.left.traverse(order)
yield self.value
self.right.traverse(order)
elif order == PREORDER:
yield self.value
self.left.traverse(order)
self.right.traverse(order)
. . .
Raymond Hettinger
More information about the Python-list
mailing list