亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

計算圓形數組中元素之間的距離

計算圓形數組中元素之間的距離

POPMUISE 2023-10-11 16:09:25
people = ["James","COP","George","COP","Sam","Mac","Johnny","Karina"]cops = [(idx+1) for idx, val in enumerate(people) if val == "COP"]  #cops' positionspeoplePositions = [(x+1) for x in range(len(people))] #index positionsdistances = []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) 進行距離的嵌套循環,但沒有任何進展。
查看完整描述

1 回答

?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

您需要計算每個人到每個 的最小距離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']


查看完整回答
反對 回復 2023-10-11
  • 1 回答
  • 0 關注
  • 112 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號