1

I'm a beginner trying to use python. The code I'm working with is from http://www.python.org/doc/essays/graphs/ The goal is to obtain a path between two nodes using a dictionary and a recursive function. When I run it, I don't get any output or any errors. I'm mainly looking for somekind of pointer as to what could cause this.

def find_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if not graph.has_key(start):
        return None
    for node in graph[start]:
        if node not in path:
            newpath = find_path(graph, node, end, path)
            if newpath: return newpath
    return None

graph = {'A': ['B','C'],'B': ['C','D'],'C': ['D'],'D': ['C'],'E': ['F'],'F':   ['C']}   
find_path(graph,'A','D')    
Bach
  • 6,145
  • 7
  • 36
  • 61
  • 7
    Do you have a `print` or output statement not included in the above code? If not, try `print find_path(graph,'A','D')` and see what happens. – mdml Mar 06 '14 at 17:53
  • 1
    Also, [you may want to change that default `path` value](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument). It's not causing problems at the moment, but it's quite likely to become a bug without you noticing if you change `find_path` at all. – user2357112 Mar 06 '14 at 17:59
  • adding print did fix it. I got a long way to go I guess. – user3389446 Mar 06 '14 at 18:02

1 Answers1

1

After running your path finder, you need to output the result somehow. One way is to just use Python's built-in print function which will output your path to standard out (your terminal or console). E.g.

print find_path(graph, 'A', 'D')
mdml
  • 22,442
  • 8
  • 58
  • 66