そこで、networkxを使用して最短パスを計算するコードを作成しています。numpyを使用して3D配列を作成し、次のように最短経路を計算しました。
import numpy as np
import networkx as nx
arr = np.random.randint(1, 100, size = (2, 5, 5)) #3D array
for i in arr:
graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
path = nx.shortest_path(graph, 0, 3, weight = 'weight')
print(path)
2つの行列を使用しているので、次の出力が得られました。
[0, 1, 3] #path1
[0, 3] #path2
その後、次のようにまったく同じことを行う関数を作成することにしました。
import numpy as np
import networkx as nx
arr = np.random.randint(1, 100, size = (2, 5, 5)) #3D array
def shortest(prices):
for i in arr:
graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
path = nx.shortest_path(graph, 0, 3, weight = 'weight')
return path
print(shortest(arr))
そして私は次の出力を得ました:
[0, 1, 3] #same as path 1
そして、私がこのように「リターンパス」の位置を変更した場合:
def shortest(precios):
for i in arr:
graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
path = nx.shortest_path(graph, 0, 3, weight = 'weight')
return path
print(shortest(arr))
次の出力が得られました:
[0, 3] #same as path 2
関数を使用して、同じ出力で2つのパスを取得できません。ここで何が起こっているのか分かりますか?私はこのトピックに少し慣れていないので、Pythonで関数を使用する練習をしていたので、何が問題なのかを確認するのに役立つことを望んでいました。ありがとうございました!
これは、とは何の関係もありませんnetworkx
かをnumpy
。これは単純な制御フローです。「最短パス」ループは、提供されたグラフを反復処理し、それぞれの最短パスを見つけます。
非機能バージョンは、見つかった各パスを出力しますが、一度に1つしか処理しません。見つかったソリューションを集約するためのプロビジョニングを関数に作成しなかったため、一度に1つしか取得できません...つまり、関数の場合、取得できるのは1つだけです。
このコードは、最初の解決策が見つかるとすぐに返されます。
for i in arr:
graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
path = nx.shortest_path(graph, 0, 3, weight = 'weight')
return path # The function ends as soon as it gets here: you get only the first solution.
このコードはすべての解決策を見つけますが、次の解決策が見つかるとすぐにそれぞれを破棄します。
for i in arr:
graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
path = nx.shortest_path(graph, 0, 3, weight = 'weight')
# You just deleted the previous solution, and replaced it with another.
return path
上書きしなかったのは最後のソリューションだけなので、これは最後のソリューションのみを返します。どういうわけかソリューションを蓄積して一緒に返すか、関数の使用法を変更する必要があります。例えば:
all_path = []
for i in arr:
graph = nx.from_numpy_array(i, create_using = nx.DiGraph)
all_path.append( nx.shortest_path(graph, 0, 3, weight = 'weight') )
return all_path
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加