首页 > 解决方案 > 计算圆形数组中元素之间的距离

问题描述

people = ["James","COP","George","COP","Sam","Mac","Johnny","Karina"]

cops = [(idx+1) for idx, val in enumerate(people) if val == "COP"]  #cops' positions
peoplePositions = [(x+1) for x in range(len(people))] #index positions
distances = []
for x in peoplePositions:
    for y in cops:
        distances.append(abs(x-y))

#the output would be "Johnny" 

大家好!我正在研究这个问题,基本上我有一个包含一些人/对象的列表,实际上是一个圆桌,即它的头部连接到它的尾部。现在我想获取“COP”和人之间的距离(索引位置),然后输出与“COP”距离最大的人。如果他们都获得相同的距离,则输出必须是所有的。

这是我的代码,最后我得到了所有人和“警察”之间的距离。我想过用一系列 len(peoplePositions) 和一系列 len(cops) 在距离范围内创建一个嵌套循环,但我没有进展。

标签: pythonarrayscircular-buffercircular-list

解决方案


您需要计算每个人到每个人的最小距离COP。这可以计算为:

min((p - c) % l, (c - p) % l)

其中p是人的索引,c是数组的索引COPl长度。然后,您可以计算这些距离的最小值,以获得从一个人到任何COPs 的最小距离。然后,您可以计算这些值的最大值,并people根据它们的距离是否等于最大值来过滤数组:

people = ["James","COP","George","COP","Sam","Mac","Johnny","Karina"]
cops = [idx for idx, val in enumerate(people) if val == "COP"]
l = len(people)
distances = [min(min((p - c) % l, (c - p) % l) for c in cops) for p in range(l)]
maxd = max(distances)
pmax = [p for i, p in enumerate(people) if distances[i] == maxd]
print(pmax)

输出:

['Johnny']

推荐阅读