gpt4 book ai didi

python - 函数: Returning min value in dictionary

转载 作者:行者123 更新时间:2023-12-01 03:36:01 25 4
gpt4 key购买 nike

我很难理解字典功能。我试图编写的函数需要找到当前位置的最近位置(在字典中给出)并返回它。我被告知涉及一个距离公式,但不确定如何将其实现到函数字典中。当没有找到任何内容时,它应该不返回任何内容。

def closest_location(d, place, now):
close_lst = []# New list
for d in closest.place():
for d in closest.now():
if now != place:
return None
elif now <= place: #If location at now is less than place we want to go to...
close_val = now - place
close_lst.append(close_val)
return(min(d, key=close_lst.get))# returns closest value in list?

测试:

check that closest({(3,1):'gas', (1,4):'gas', (2,1):'food', (5,5):'food'},'food',(5,5)) == (5,5).
check that closest({(3,1):'gas', (1,4):'gas', (2,1):'food', (5,5):'food'},'hotel',(1,4)) == None.

最佳答案

假设元组是网格上的 x,y 坐标,距离公式由毕达哥拉斯给出:

(x1 - x2)^2 + (y1 - y2)^2 = distance^2

我们只是将其提取到它自己的函数中以提高可读性。

from math import sqrt
def find_distance(a,b):
ax, ay = a
bx, by = b
return sqrt((ax-bx)**2 + (ay-by)**2)

def closest_location(d, place, now):
locations = [loc for loc, attraction in d.items() if attraction==place]
if not locations:
return None
else:
return min(locations, key=lambda x: find_distance(x, now))

关于python - 函数: Returning min value in dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40385898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com