Returning from a multiple stacked call at once

jak nospam at please.ty
Tue Dec 15 06:31:21 EST 2020


Il 12/12/2020 07:39, ast ha scritto:
> Hello
> 
> In case a function recursively calls itself many times,
> is there a way to return a data immediately without
> unstacking all functions ?
> 

try this way:

def path_finder(graph, start, end, path=[]):
     if start in path:
         yield None
     if start == end:
         yield path + [start]  # Found !
     if start not in graph:
         yield None

     path = path + [start]

     for node in graph[start]:
         found_path = yield from path_finder(graph, node, end, path)
         if found_path:
             yield found_path
     yield None


graph = {'A': ['B', 'C'],
          'B': ['C', 'D'],
          'C': ['D'],
          'D': ['C'],
          'E': ['F'],
          'F': ['C']}
result = []
for r in path_finder(graph, 'A', 'D'):
     result = r
     break
print(result)


More information about the Python-list mailing list