【问题标题】:Calculate the distances between elements in a circular array计算圆形数组中元素之间的距离
【发布时间】:2021-01-20 20:14:03
【问题描述】:
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) 范围在距离范围内创建一个嵌套循环,但我没有进展。

【问题讨论】:

  • 什么是peoplePositions
  • 这是人的索引位置。
  • 如果您的代码定义了所有变量,这将有所帮助。有很多方法可以解释变量的描述。但是如果你真的在代码中定义了,那么我们就没有机会弄错了。
  • 哦,对不起!我只是错过了代码。现在是正确的。
  • 另外,我不明白最后的评论the output would be "Johnny"。此代码没有打印语句,因此没有输出。你期待“约翰尼”来自哪里?

标签: python arrays circular-buffer circular-list


【解决方案1】:

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

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

其中p 是人的索引,cCOP 的索引,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']

【讨论】:

    猜你喜欢
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多