質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

1回答

2621閲覧

Pythonにおけるdaijkstra法を用いてあるノード(x,y)の最短経路の長さを求める関数f(x,y)を作りたい

tiadia

総合スコア13

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2019/07/15 07:44

編集2019/07/15 08:12

前提・実現したいこと

daijkstra法を用いてあるノード(x,y)の最短経路の長さを求める関数f(x,y)を作りたい

発生している問題・エラーメッセージ

エラーメッセージ

Warning (from warnings module):
File "C:\Users\stuart\AppData\Local\Programs\Python\Python37\lib\site-packages\networkx\drawing\nx_pylab.py", line 579
if not cb.iterable(width):
MatplotlibDeprecationWarning:
The iterable function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use np.iterable instead.
Traceback (most recent call last):
File "F:\7.9卒論.py", line 78, in <module>
for source, mapping in all_pairs:
File "C:\Users\stuart\AppData\Local\Programs\Python\Python37\lib\site-packages\networkx\algorithms\shortest_paths\weighted.py", line 1049, in all_pairs_dijkstra_path_length
yield (n, length(G, n, cutoff=cutoff, weight=weight))
File "C:\Users\stuart\AppData\Local\Programs\Python\Python37\lib\site-packages\networkx\algorithms\shortest_paths\weighted.py", line 373, in single_source_dijkstra_path_length
weight=weight)
File "C:\Users\stuart\AppData\Local\Programs\Python\Python37\lib\site-packages\networkx\algorithms\shortest_paths\weighted.py", line 623, in multi_source_dijkstra_path_length
return _dijkstra_multisource(G, sources, weight, cutoff=cutoff)
File "C:\Users\stuart\AppData\Local\Programs\Python\Python37\lib\site-packages\networkx\algorithms\shortest_paths\weighted.py", line 831, in _dijkstra_multisource
vu_dist = dist[v] + cost
TypeError: unsupported operand type(s) for +: 'int' and 'str'

自作のプログラム

Python

1import networkx as nx 2import matplotlib.pyplot as plt 3import numpy as np 4 5G=nx.Graph() 6 7#ノードの座標の設定 8pos={1:(0,4), 9 2:(2,10), 10 3:(4,4), 11 4:(3,0), 12 5:(10,11), 13 6:(9,4), 14 7:(11,0), 15 8:(15,7), 16 9:(13,2)} 17 18nx.draw(G,pos) 19 20#ユークリッド距離 21x=pos 22y=pos 23def ans(x,y): 24 vec = np.array(pos[x])-np.array(pos[y]) 25 dist1 = np.linalg.norm(vec) 26 return f"{dist1:4.2f}" 27 28#枝とその重みの設定 29G.add_weighted_edges_from([(1,2,ans(1,2)), 30 (1,3,ans(1,3)), 31 (1,4,ans(1,4)), 32 (2,3,ans(2,3)), 33 (3,4,ans(3,4)), 34 (2,5,ans(2,5)), 35 (3,6,ans(3,6)), 36 (4,7,ans(4,7)), 37 (5,6,ans(5,6)), 38 (6,7,ans(6,7)), 39 (5,8,ans(5,8)), 40 (8,9,ans(8,9)), 41 (6,9,ans(6,9)), 42 (7,9,ans(7,9))]) 43 44 45#枝の長さをラベルとして設定 46edge_labels={(1,2):ans(1,2), 47 (1,3):ans(1,3), 48 (1,4):ans(1,4), 49 (2,3):ans(2,3), 50 (3,4):ans(3,4), 51 (2,5):ans(2,5), 52 (3,6):ans(3,6), 53 (4,7):ans(4,7), 54 (5,6):ans(5,6), 55 (6,7):ans(6,7), 56 (5,8):ans(5,8), 57 (8,9):ans(8,9), 58 (6,9):ans(6,9), 59 (7,9):ans(7,9)} 60 61nx.draw_networkx_nodes(G,pos) 62nx.draw_networkx_edges(G,pos,node_size=100,width=1) 63nx.draw_networkx_edge_labels(G,pos,edge_labels) 64nx.draw_networkx_labels(G,pos,font_size=12,font_color="w") 65 66#x, y座標軸の定義 67plt.xlim(-5.0, 20.0) 68plt.xticks([]) 69plt.ylim(-5.0, 15.0) 70plt.yticks([]) 71plt.show() 72 73#daijkstra法 74from networkx.algorithms.shortest_paths.weighted import all_pairs_dijkstra_path_length 75all_pairs =all_pairs_dijkstra_path_length(G) 76for source, mapping in all_pairs: 77 for target in mapping.keys(): 78 if source != target: 79 dist2 =mapping[target] 80 print(f"({source}, {target}): {dist2:4.2f}")

試したこと

まず、関数f(x,y)を作る前に各ノード(x,y)の最短経路の長さと最短経路を表示させた

補足情報(FW/ツールのバージョンなど)

元々、ans(x,y)を作る前は表示されていたが「枝とその重みの設定」と「枝の長さをラベルとして設定させる」所でans(x,y)を呼び出したらエラーするようになった。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

bamboo-nova

2019/07/15 07:46

コードを載せるときは、なるべくmarkdown記法に習って```との間に入れるようにした方が答える方が見やすいと思うので、そうしてください。
guest

回答1

0

ベストアンサー

Python

def ans(x,y):
...
dist1 = np.linalg.norm(vec)
return f"{dist1:4.2f}"

余計に文字列化の処理を噛ませているのが問題では。
単に return dist1 で充分な気がします。

Python

1>>> n = 2 2>>> 40 + n 342 4>>> 40 + str(n) 5Traceback (most recent call last): 6 File "<stdin>", line 1, in <module> 7TypeError: unsupported operand type(s) for +: 'int' and 'str'

コードの書き方について

teratailには、コードを見やすく表示する機能があります。
質問編集画面を開き、コードを選択した状態で<code>ボタンを押して下さい。
Python

特にPythonの場合、インデントが崩れるとコードの意味が変わってしまいます。

投稿2019/07/15 07:49

編集2019/07/15 07:52
LouiS0616

総合スコア35660

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

tiadia

2019/07/15 08:06

return dist1で最短経路の計算はできました!ありがとうございます。 ただ、この場合だとラベルとして表示させるdist1を小数点第二位までに収めたいのですが、それが出来なくなってしまいました。
LouiS0616

2019/07/15 08:35 編集

draw_networkx_edge_labelsにprecisionとかformatとかそういう引数があることを期待していたんですが、どうやら無さそうです。 https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.drawing.nx_pylab.draw_networkx_edge_labels.html --- networkxを使ったことが無いので遠回りな方法かもしれませんが、とりあえず次のように書けばエラー無く実行できました。結局一時的に文字列化させてます。 nx.draw_networkx_edge_labels( G, pos, edge_labels={k: '{:.2f}'.format(v) for k, v in edge_labels.items()} )
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問