使用 Python 编写程序查找具有相同 x 或 y 坐标的最近点
pythonserver side programmingprogramming更新于 2025/5/31 10:20:17
假设我们在名为 pts 的数组中给出了一组点。我们还有另一个点 (x, y),它是我们的当前位置。我们将有效点定义为与当前点共享相同 x 坐标或相同 y 坐标的点。我们必须返回距离我们当前位置 (x, y) 最小的曼哈顿距离的有效点的索引。如果有多个点,则返回索引最小的有效点。 (注意:两点 (a, b) 和 (p, q) 之间的曼哈顿距离为 |a - p| + |b - q|。
因此,如果输入为 pts = [(1,2),(3,1),(3,4),(2,3),(4,4)] pt = (2,4),则输出将为 2,因为有两个最近的点 (3,4) 和 (2,3),但 (3,4) 的索引较小。

为了解决这个问题,我们将遵循以下步骤 −
x, y := pt
idx := -1
smallest := infinity
对于 pts 中的每个 p,执行
如果 p[0] 与 x 相同或 p[1] 与 y 相同,则
dist := |x - p[0]| + |y - p[1]|
如果 dist < minimal,则
idx := p 在 pts 中的索引
smallest := dist
否则,当 dist 与 minimal 相同时,则
如果 p 在 pts 中的索引 < idx,则
idx := p 在 pts 中的索引
smallest := dist
返回 idx
让我们看看下面的实现以便更好地理解 −
示例
def solve(pts, pt):
x, y = pt
idx = -1
smallest = float("inf")
for p in pts:
if p[0] == x or p[1] == y:
dist = abs(x - p[0]) + abs(y - p[1])
if dist < smallest:
idx = pts.index(p)
smallest = dist
elif dist == smallest:
if pts.index(p) < idx:
idx = pts.index(p)
smallest = dist
return idx
pts = [(1,2),(3,1),(3,4),(2,3),(4,4)]
pt = (2,4)
print(solve(pts, pt))
输入
[(1,2),(3,1),(3,4),(2,3),(4,4)], (2,4)
输出
2
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

