Here I showed how a couple of external iterators can be implemented in Python using generators.
Now I will present a couple of internal iterators in Python performing the same tasks. The user only has to provide the callback.
def dfs(node, action): stack = [node, ] while stack: current_node = stack.pop() stack.extend(reversed(current_node.children)) action(current_node.value) def bfs(node, action): queue = collections.deque((node, )) while queue: current_node = queue.popleft() queue.extend(current_node.children) action(current_node.value) dfs(tree, lambda x: sys.stdout.write("%s, " % x))
The code comes from the presentation I gave at Pycon Italia 4.
No comments:
Post a Comment