2016-09-17 15 views
1

私はいくつかの経路発見アルゴリズムを研究しています。以下のスニペットは、目標から開始までの経路にノードの配列を作ることになっています。ゴールからスタートまでのパスがある場合はうまく動作します。しかし、最初から最後までのパスがない場合、whileループは決して実行されず、結果は[](これは正しい)として返されます。なぜ、空のリストが返されるとNoneTypeになるのですか?

<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 

答えて

3

起こっているのではない何:

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 

は、しかし、私はこのエラーを取得しています。問題は、line 46に、path()が返すリストでreverse()を呼び出した結果、start_pathを割り当てたということです。 これは問題ありませんが、[].reverse()は常にNoneを返すので、意図したとおりではありません。逆はなし戻り値の型とインプレース操作ですので

#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 
+0

または、コピーコストは構文ベースのスライスの安っぽさによって相殺されているので(メソッド呼び出しの高コストと比較して)、あなたはそれをワンライナーを保つことができます'start_path = path(center、pathBack_start)[:: - 1]'で ' – ShadowRanger

+0

私はそれを忘れてしまったと感じます。ありがとう –

1

:私はあなたがしたいと思う何

はこれです。

x = [1, 2] 
print(x) 
[1, 2] 
a = x.reverse() 
print(a) 
None 
print(x) 
[2, 1] 

逆の結果にstart_pathを割り当てないでください。

0

[].reverse()が返される場合は、リストをインプレースで変更するため、戻り値を割り当てるべきではありません。

は、以下を参照してください。代わりに

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 
>>> 
関連する問題