I'm working on some path finding algorithms, and the snippet below is supposed to make an array of nodes in the path from the goal to the start. It works fine when there is a path from the goal to the start. But when there is no path from start to goal, the while loop never runs, and result gets returned as []
(which is correct).
def path(goal, pathToParentLookup):
currentNode = goal
result = []
while(currentNode in pathToParentLookup):
currentNode = pathToParentLookup[currentNode]
result.append(currentNode)
return result
#bidirectional search from start to goal finds the mid point of "center"
start_path = path(center, pathBack_start).reverse()
goal_path = path(center, pathBack_goal)
return start_path + [center] + goal_path
However I'm getting this error:
<ipython-input-14-ca3cb26b31ce> in bidirectional_search(graph, start, goal, searchMethod)
46 start_path = path(center, pathBack_start).reverse()
47 goal_path = path(center, pathBack_goal)
---> 48 return start_path + [center] + goal_path
49
50
TypeError: can only concatenate list (not "NoneType") to list
That's not what is happening. The problem is that on line 46
you assign start_path the result of calling reverse() on the list that path()
returns.
That's OK, but since [].reverse()
always returns None
, I'm certain it's not what you intended.
What I think you want is this:
#bidirectional search from start to goal finds the mid point of "center"
start_path = path(center, pathBack_start)
start_path.reverse()
goal_path = path(center, pathBack_goal)
return start_path + [center] + goal_path