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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With