简体   繁体   中英

Why does an empty list become NoneType on return?

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

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()

[].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
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM