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

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”距离最大的人。如果它们都具有相同的距离,则输出必须是它们全部。


这是我的代码,最后我得到了所有人和“COP”之间的距离。我考虑过用一系列 len(peoplePositions) 和一系列 len(cops) 进行距离的嵌套循环,但没有任何进展。


POPMUISE
浏览 95回答 1
1回答

Cats萌萌

您需要计算每个人到每个 的最小距离COP。这可以计算为:min((p - c) % l, (c - p) % l)其中p是 person 的索引,c是 the 的索引COP以及l数组的长度。然后,您可以计算这些距离的最小值,以获得从一个人到任何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']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python