Le 12/12/2020 à 09:18, Cameron Simpson a écrit :
On 12Dec2020 07:39, ast <ast@invalid> wrote:
In case a function recursively calls itself many times,
is there a way to return a data immediately without
unstacking all functions ?

Not really. Do you have an example where this is inconvenient?

There are alternatives, for example passing in a Queue and put()ing the
data onto the queue. It's quite dependent on what you're trying to do
though.

Cheers,
Cameron Simpson <c...@cskk.id.au>


I don't really need it. I was just wondering and guessed it was
not feasible.

Here is a code where it would be useful. This code looks for a
path in a graph.
If the found path is long, say 100 nodes, then path_finder calls
itself recursively 100 times, and has to unstack 100 times to
provide the found path. It could be returned immediately.


def path_finder(graph, start, end, path=[]):    

        if start in path:
                return None
        if start == end:
                return path + [start]   # Found !
        if start not in graph:
                return None
        
        path = path + [start]

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

graph = {'A': ['B', 'C'],
             'B': ['C', 'D'],
             'C': ['D'],
             'D': ['C'],
             'E': ['F'],
             'F': ['C']}

path_finder(graph, 'A', 'D')
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to