I am writing a width function to traverse a tree in depth, and I want to do this:
def traverse(node):
yield node
for n in node.children:
yield_all traverse(n)
The idea is to complete a (flat) sequence of nodes in a tree.
Approach # 1: (distributed outputs)
def traverse(node):
yield node
for n in node.children:
for m in traverse(n):
yield m
Approach No. 2: (smoothing sequences)
def traverse(node):
return itertools.chain([node],*(traverse(n) for n in node.children))
The first approach seems cleaner, but I feel weirdly explicitly yieldentering each node in a subtree at each level.
The second approach is concise and slightly dirty, but it corresponds to what I would write in Haskell:
traverse node = node : concatMap traverse (children node)
So my question is: which is better? Or did I miss the best third option?
source
share