回答編集履歴
3
元コードに対する対応を追記
test
CHANGED
@@ -23,3 +23,43 @@
|
|
23
23
|
print(nearest, pref_capitals[nearest])
|
24
24
|
|
25
25
|
```
|
26
|
+
|
27
|
+
|
28
|
+
|
29
|
+
元のやり方なら、keysのイテレータを作って、nextで最初の要素を取り出して仮の最小値にして、残りのkyesでループするのが楽です。
|
30
|
+
|
31
|
+
|
32
|
+
|
33
|
+
```
|
34
|
+
|
35
|
+
pref_capitals = {(43.06417, 141.34694): "北海道(札幌)",
|
36
|
+
|
37
|
+
(40.82444, 140.74): "青森県(青森市)",
|
38
|
+
|
39
|
+
(39.70361, 141.1525): "岩手県(盛岡市)"
|
40
|
+
|
41
|
+
}
|
42
|
+
|
43
|
+
loc = (41, 141)
|
44
|
+
|
45
|
+
|
46
|
+
|
47
|
+
keys = iter(pref_capitals.keys())
|
48
|
+
|
49
|
+
key = next(keys)
|
50
|
+
|
51
|
+
min_calc = (key[0] - loc[0])**2 + (key[1] - loc[1])**2
|
52
|
+
|
53
|
+
|
54
|
+
|
55
|
+
for key in keys:
|
56
|
+
|
57
|
+
calc = (key[0] - loc[0])**2 + (key[1] - loc[1])**2
|
58
|
+
|
59
|
+
if min_calc > calc:
|
60
|
+
|
61
|
+
min_calc = calc
|
62
|
+
|
63
|
+
print(min_calc)
|
64
|
+
|
65
|
+
```
|
2
説明追加
test
CHANGED
@@ -1,3 +1,7 @@
|
|
1
|
+
一番近い、距離が一番小さい、min関数の出番。
|
2
|
+
|
3
|
+
|
4
|
+
|
1
5
|
```
|
2
6
|
|
3
7
|
pref_capitals = {(43.06417, 141.34694): "北海道(札幌)",
|
1
コード変更
test
CHANGED
@@ -14,15 +14,7 @@
|
|
14
14
|
|
15
15
|
loc = (41, 141)
|
16
16
|
|
17
|
-
|
18
|
-
|
19
|
-
def distance(geo):
|
20
|
-
|
21
|
-
|
17
|
+
nearest = min(pref_capitals, key=lambda geo: (loc[0] - geo[0])**2 + (loc[1] - geo[1])**2)
|
22
|
-
|
23
|
-
|
24
|
-
|
25
|
-
nearest = min(pref_capitals, key=distance)
|
26
18
|
|
27
19
|
print(nearest, pref_capitals[nearest])
|
28
20
|
|