teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

2

修正

2021/10/21 12:03

投稿

8524ba23
8524ba23

スコア38352

answer CHANGED
@@ -11,11 +11,12 @@
11
11
  import random
12
12
  import math
13
13
 
14
- # ノード。5x5の碁盤目状の20個
14
+ # ノード。碁盤目状に配置
15
+ N, D = 10, 0.95 # 碁盤の大きさ, ノードの密度
15
16
  random.seed(110)
16
- pos = list(product(range(5), repeat=2))
17
+ pos = list(product(range(N), repeat=2))
17
18
  random.shuffle(pos)
18
- pos = {f'{p[0]}{p[1]}':p for p in pos[:20]}
19
+ pos = {f'{p[0]}{p[1]}':p for p in pos[:int(len(pos)*D)]}
19
20
 
20
21
  # エッジ。ノード間の距離が1以下
21
22
  nodes = pos.keys()
@@ -32,4 +33,7 @@
32
33
  nx.draw(G, pos=pos, with_labels=True)
33
34
  plt.show()
34
35
  ```
36
+ 密度=0.5
37
+ ![イメージ説明](1842eaeaf383da268e54c6b94fe434d2.png)
38
+ 密度=0.95
35
- ![イメージ説明](671d66d3c9066bd58f0d5da8e0a22cdb.png)
39
+ ![イメージ説明](e4bf3a1d25787b0a6bbe91ea400fc894.png)

1

修正

2021/10/21 12:03

投稿

8524ba23
8524ba23

スコア38352

answer CHANGED
@@ -7,14 +7,29 @@
7
7
  ```Python
8
8
  import matplotlib.pyplot as plt
9
9
  import networkx as nx
10
- from itertools import combinations
10
+ from itertools import combinations, product
11
+ import random
12
+ import math
11
13
 
14
+ # ノード。5x5の碁盤目状の20個
15
+ random.seed(110)
16
+ pos = list(product(range(5), repeat=2))
17
+ random.shuffle(pos)
12
- pos = {'a': [10, 10], 'b': [20, 10], 'c': [20, 20], 'd':[10,20]}
18
+ pos = {f'{p[0]}{p[1]}':p for p in pos[:20]}
19
+
20
+ # エッジ。ノード間の距離が1以下
21
+ nodes = pos.keys()
22
+ edges = []
23
+ for n1, n2 in combinations(nodes, 2):
24
+ p1, p2 = pos[n1], pos[n2]
25
+ if math.sqrt(abs(p1[0]-p2[0]) + abs(p1[1]-p2[1])) <= 1:
26
+ edges.append((n1, n2))
27
+
13
28
  G = nx.Graph()
14
- G.add_nodes_from(pos.keys())
29
+ G.add_nodes_from(nodes)
15
- G.add_edges_from(combinations(pos.keys(),2))
30
+ G.add_edges_from(edges)
16
31
 
17
32
  nx.draw(G, pos=pos, with_labels=True)
18
33
  plt.show()
19
34
  ```
20
- ![イメージ説明](60bba569350ba48901d59e7a1b03cb8d.png)
35
+ ![イメージ説明](671d66d3c9066bd58f0d5da8e0a22cdb.png)