Reputation: 13
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
Upvotes: 1
Views: 1188
Reputation: 11287
[].reverse()
returns None
, you should not assign the return value, because it modifies the list in-place.
See below:
Python 2.7.11 (default, Dec 5 2015, 14:44:53)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.1.76)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print [].reverse()
None
>>>
Upvotes: 0
Reputation: 5238
Because reverse is an inplace operation with a None return type.
x = [1, 2]
print(x)
[1, 2]
a = x.reverse()
print(a)
None
print(x)
[2, 1]
Don't assign start_path
to the result of reverse. Assign it to start_path = path(center, pathBack_start) and then call start_path.reverse()
Upvotes: 1
Reputation: 6291
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
Upvotes: 3