Created
July 15, 2014 11:55
-
-
Save brandon-rhodes/7ba1582c65a817ac3bcd to your computer and use it in GitHub Desktop.
Two-level breadth-first descent using a generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Generators leave it up to the caller whether | |
# to build a list, or set, or maybe just to | |
# loop and not build a data structure at all: | |
def get_children(self): | |
for c in self.children.itervalues(): | |
yield c | |
for c in self.children.itervalues(): | |
for c2 in c.get_children(): | |
yield c2 | |
... | |
# Then, later: | |
children = list(obj.get_children()) | |
# Yes, it was finicky of me to use itervalues() | |
# but if I am going to illustrate zero-data- | |
# structure iteration, then I might as well go | |
# the whole way. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment