python - 计算圆形数组中元素之间的距离
问题描述
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) 在距离范围内创建一个嵌套循环,但我没有进展。
解决方案
您需要计算每个人到每个人的最小距离COP
。这可以计算为:
min((p - c) % l, (c - p) % l)
其中p
是人的索引,c
是数组的索引COP
和l
长度。然后,您可以计算这些距离的最小值,以获得从一个人到任何COP
s 的最小距离。然后,您可以计算这些值的最大值,并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']
推荐阅读
- .net-core - 使用“.NETFramework,Version=v4.6.1”而不是项目目标框架来恢复包“GuerrillaSharp 1.0.0”
- c++ - 导入 Assimp:Assimp.xcodeproj 项目失败构建错误
- android - 如何将数组从firestore转换为字符串以显示在viewholder textview中
- javascript - 过滤对象,调整并替换
- zapier - 有没有办法通过红旗和电子邮件通知让 Zaps 故意“停止”?
- redirect - 测试多个域名服务器后从广告中取回 cPanel?
- bash - 如何从 Bash 中的字符串中提取部分 IP 地址
- c# - WPF 弹出窗口意外关闭
- android - Kotlin 中的奇怪行为
- php - 无法从 Swagger API 文档中获取数据