计算圆形数组中元素之间的距离

问题描述

people = ["James","cop","George","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)在距离之间进行嵌套循环,但是我没有任何进展。

解决方法

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

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

其中p是人的索引,cCOP的索引,而l是数组的长度。然后,您可以计算这些距离中的最小距离,以获得从人到任何COP的最小距离。然后,您可以计算这些值的最大值,并根据其距离等于最大值来过滤people数组:

people = ["James","COP","George","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']

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...