複数の座標の中から一番距離の近い座標を求める関数を作ってみました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import math # 複数の座標のうちx, yに一番近い座標を求める def nearPoint(x, y, points): result = {} if len(points) == 0: return result result["x"] = points[0]["x"] result["y"] = points[0]["y"] stdval = math.sqrt((points[0]["x"] - x) ** 2 + (points[0]["y"] - y) ** 2) for point in points: distance = math.sqrt((point["x"] - x) ** 2 + (point["y"] - y) ** 2) if stdval > distance: result["x"] = point["x"] result["y"] = point["y"] stdval = distance return result |
実際に動かしてみます。
1 2 3 4 5 6 7 8 9 10 11 12 |
# -*- coding: utf-8 import json points = [] points.append({"x": 5, "y": 5}) points.append({"x": 5, "y": 10}) points.append({"x": -10, "y": 5}) points.append({"x": 3, "y": 4}) points.append({"x": -5, "y": -5}) # (3, 10)に一番近い座標を求める print("(3, 10)に一番近い座標を求める") print(json.dumps(nearPoint(3, 10, points), indent=4)) |
1 2 3 4 5 |
(3, 10)に一番近い座標を求める { "x": 5, "y": 10 } |
