A question from code in python's graph theory essays
The code is to determine a path between two nodes for directed graphs. This is the code:
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]:
开发者_StackOverflow社区 if node not in path:
newpath = find_path(graph, node, end, path)
if newpath: return newpath
return None
Being new to python, I two have small and trivial questions. I hope you don't mind it.
Q1. What does if newpath:
in the second last line of the code mean?
Q2. Does this code gives all possible paths in the directed graph?
Thanks.
Q1: This checks whether the call of find_path actually returns something. See the language docs to find out what gets interpreted as true and what as false if the type of the term is not boolean to start with. (In this case, None evaluates to false).
Q2: No: this function gives exactly one path from start to end.
精彩评论