2016-11-02 2 views
1

사전 기능을 이해하는 데 어려움이 있습니다. 필자가 작성하려고하는 함수는 현재 위치가 가장 가까운 위치 (사전에 있음)를 찾아 반환해야합니다. 거리 공식이 포함되어 있지만 함수 사전에 구현하는 방법을 모르겠다 고 들었습니다. 아무 것도 발견되지 않으면 아무 것도 반환하지 않습니다.함수 : 사전에서 최소값 반환

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. 
+1

무엇이'closest.what()'와'closest.now()'입니까? 정의 된 부분은 어디에 있습니까? –

+0

유클리드 (x, y) 평면처럼 보입니까? [거리 공식] (http://www.cut-the-knot.org/pythagoras/DistanceFormula.shtml) – CAB

+0

예, 간단 (x, y). –

답변

2

튜플 가정이 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))