Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a better recursive depth-first search in python

Tags:

python

I'm trying to build a graph library in python (along with standard graph-algorithms). I've tried to implement DFS and this is what it looks like

def DFS(gr, s, path):
    """ Depth first search 
    Returns a list of nodes "findable" from s """
    if s in path: return False
    path.append(s)
    for each in gr.neighbors(s):
        if each not in path:
            DFS(gr, each, path)

This is working fine but I'm not happy with how it needs to be used. E.g. currently you need to do this

 path = []
 DFS(mygraph, "s", path)
 print path

Instead of this, I want to DFS to be used in this manner

path = DFS(mygraph, "s")
print path

With the recursive DFS, I am unable to come up with the implementation that works like above. Can someone give me some pointers on how can I achieve this?

like image 962
Prakhar Avatar asked Feb 19 '23 07:02

Prakhar


1 Answers

Just make a wrapper method that calls the one you already have:

def DFS(gr, s):
    path = []
    DFS2(gr, s, path)
    return path

Here DFS2 is the method you showed above.

like image 68
Sebastian Paaske Tørholm Avatar answered Feb 21 '23 01:02

Sebastian Paaske Tørholm