これは、ルーマニアの都市をナビゲートするpythonの検索アルゴリズムです。未定義のエラーが発生し続けるのはなぜですか?
class GraphTree:
graph = {
'Oradea': set(['Zerind','Sibiu']),
'Zerind': set(['Arad','Oradea']),
'Sibiu': set(['Arad','Rimnicu Vilcea','Fagaras','Oradea']),
'Arad': set(['Timisoara','Zerind','Sibiu']),
'Timisoara': set(['Lugoj']),
'Lugoj': set(['Mehadia']),
'Mehadia': set(['Drobeta']),
'Drobeta': set(['Craiova']),
'Rimnicu Vilcea': set(['Craiova','Pitesti','Sibiu']),
'Craiova': set(['Drobeta','Rimnicu Vilcea']),
'Fagaras': set(['Bucharest','Sibiu']),
'Pitesti': set(['Bucharest','Rimnicu Vilcea']),
'Bucharest': set(['Giurgiu','Urziceni','Pitesti','Fagaras']),
'Giurgiu': set(['Bucharest']),
'Urziceni': set(['Hirsova','Vaslui','Bucharest']),
'Hirsova': set(['Eforia','Urziceni']),
'Eforia': set(['Hirsova']),
'Vaslui': set(['Iasi','Urziceni']),
'Iasi': set(['Neamt','Vaslui']),
'Neamt': set(['Iasi'])}
def bfs(graph, start, end):
queue = [(start, [start])]
while queue:
(vertex, path) = queue.pop(0)
for next in graph[vertex] - set(path):
if next == end:
yield path + [next]
else:
queue.append((next, path + [next]))
def dfs(graph, start, goal):
queue = []
queue.append([start])
while queue:
path = queue.pop(0)
node = path[-1]
if node == end:
return path
for adjacent in graph.get(node,[]):
new_path = list(path)
new_path.append(adjacent)
queue.append(new_path)
print('bfs')
bfs(graph, 'Oradea', 'Neamt')
print('dfs')
dfs(graph, 'Oradea', 'Neamt')
私はアルゴリズムを実行したときに、私はこのエラーを取得しておいてください。
---> 1 class GraphTree:
2
3 graph = {
4 'Oradea': set(['Zerind','Sibiu']),
5 'Zerind': set(['Arad','Oradea']),
でもう1: 49 BFS(グラフ、 'オラデア'、 'ネアムツ') 50プリント( 'DFS' ) - > 51のDFS(グラフ、 'オラデア'、 'ネアムツ')
そして最後:
39 path = queue.pop(0)
40 node = path[-1]
- > 41であればノード==終了:graph.getに隣接するため 42リターンパス 43(ノード、[]):
NameError: name 'end' is not defined
アルゴリズムが条件と宣言OKと論理的に正しいと思われます。 この検索アルゴリズムが機能しないのはなぜですか?
The algorithm should be able to navigate the map going from one city to the other and returning the path using both breadth first (bfs) and depth first (dfs) searches.
は、このメソッドでは最後に定義されていますか? –
完全なエラーメッセージ(コンパイラによって与えられる)、関連する行番号などを提供してください。これにより、StackOverflowユーザーがあなたを助けやすくなります。また、場合によっては、自分でその行を検査することで、すぐに問題を認識するのに役立ちます。 –
'dfs()'パラメータで 'end'の代わりに' goal'という名前を使用しましたが、 'if node == end:'にしようとしました。 –