问题描述
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
是人的索引,c
是COP
的索引,而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']