I have a generator that gives nodes from a Directed Acyclic Graph (DAG), first depth:
def depth_first_search(self):
yield self, 0
for child in self.get_child_nodes():
for node, depth in child.depth_first_search():
yield node, depth+1
I can iterate over nodes like this
for node, depth in graph.depth_first_search():
I would like to be able to tell the generator from the for loop to stop going deeper in the graph if any condition is met.
I came up with the following solution using an external function.
def depth_first_search(self, stop_crit=lambda n,d: False):
yield self, 0
for child in self.get_child_nodes():
for node, depth in child.depth_first_search():
yield node, depth+1
if stop_crit(node, depth): break
This solution forces me to declare the variables that I need before stop_crit is defined so that I can access them.
In Ruby, income returns the last expression from a block, so it’s convenient to use it to make the generator continue or stop.
What is the best way to implement this function in Python?