0

here are my python code for dfs path search:

class Graph(object):
   def __init__(self,dict=None):
       Graph.node = dict if dict != None else {}
   def add_node(self,nodedict):
       self.node = dict(self.node,**nodedict)
   def traversal_dfs(self,start,target,path = []):
       path = path + [start]
       for vertex in self.node[start]:
           print path,vertex,target
           if vertex == target:
               return path + [vertex]
           elif vertex not in path:
               path = self.traversal_dfs(vertex,target,path)
if __name__ == "__main__":
    g = Graph({'a':['b','c'],'b':['c','e'],'c':['d'],'d':['e'],'e':['f','a'],'f':['b']})
    print g.traversal_dfs('a','f')

But when I run it, I got errors like that:

Traceback (most recent call last):
  File "/Users/zzzyui/PycharmProjects/python_test/Traversal.py", line 25, in <module>
['a'] b f
    print g.traversal_dfs('a','f')
['a', 'b'] c f
['a', 'b', 'c'] d f
['a', 'b', 'c', 'd'] e f
  File "/Users/zzzyui/PycharmProjects/python_test/Traversal.py", line 19, in traversal_dfs
['a', 'b', 'c', 'd', 'e'] f f
    path = self.traversal_dfs(vertex,target,path)
stop flag
None e f
  File "/Users/zzzyui/PycharmProjects/python_test/Traversal.py", line 18, in traversal_dfs
    elif vertex not in path:
TypeError: argument of type 'NoneType' is not iterable

I wonder why the condition vertex == target does not work and how to fix it?

3
  • As seen in the Traceback, elif vertex not in path: is the line causing the problem. Seems path is None. Catch the exception and in the except suite, inspect path and anything else that may be relevant - printing is a good start. Commented Jul 29, 2017 at 15:08
  • def __init__(self,dict=None): ... You shouldn't use variable names that shadow Python keywords or builtins. Commented Jul 29, 2017 at 15:13
  • 1
    def traversal_dfs(self,start,target,path = []): mutable default arguments can give you headaches. Commented Jul 29, 2017 at 15:17

1 Answer 1

1

you should add a return statement in elif statement. for e.g return path

Sign up to request clarification or add additional context in comments.

1 Comment

Like return self.traversal_dfs(vertex,target,path) intead of path = ...?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.