2015-01-16 3 views
0

중첩 된 사전을 사용하여 계산을 수행하는 파이썬 프로그램이 있습니다. 문제는 누군가 사전에없는 값을 입력하면 작동하지 않는다는 것입니다. 사용자가 값 중에서 선택하도록 강요 할 수도 있지만 '예상'값을 얻기 위해 보간법을 수행합니다. 나는이 사전들을 풀고, 명령을 내리고, 보간법을 수행하는 방법을 알아낼 수 없다.사전 파이썬 3의 데이터 보간

도움을 주시면 감사하겠습니다. 내 코드는 아래와 같습니다. 이 같은

사전 :

from decimal import * 
pga_values = { 
    "tee": { 
     100:2.92, 120:2.99, 140:2.97, 160:2.99, 180:3.05, 200:3.12,  240:3.25, 260:3.45, 280:3.65, 
    300:3.71, 320:3.79, 340:3.86, 360:3.92, 380:3.96, 400:3.99, 420:4.02, 440:4.08, 460:4.17, 
    480:4.28, 500:4.41, 520:4.54, 540:4.65, 560:4.74, 580:4.79, 600:4.82 
}, 
"fairway": { 
    5:2.10,10:2.18,20:2.40,30:2.52,40:2.60,50:2.66,60:2.70,70:2.72,80:2.75, 

ETC ... 문제를 조금 분리

lie_types = set(pga_values.keys()) 
user_preshot_lie = input("What was your pre-shot lie type?") 
user_preshot_distance_to_hole = Decimal(input('How far away from the hole were you before your shot?')) 
user_postshot_lie = input("What was your post-shot lie type?") 
user_postshot_distance_to_hole = Decimal(input('How far away from the hole were you?')) 
assert user_preshot_lie in lie_types 
assert user_postshot_lie in lie_types 

preshot_pga_tour_shots_to_hole_out = pga_values[user_preshot_lie][user_preshot_distance_to_hole] 
postshot_pga_tour_shots_to_hole_out = pga_values[user_postshot_lie][user_postshot_distance_to_hole] 

user_strokes_gained = Decimal((preshot_pga_tour_shots_to_hole_out -  postshot_pga_tour_shots_to_hole_out)-1) 

print(user_strokes_gained) 

답변

1

을 감안할 때 예 (간결 편집) :

tee = { 
    100:2.92, 120:2.99, 140:2.97, 160:2.99, 180:3.05, 200:3.12, 240:3.25, 260:3.45, 280:3.65, 
300:3.71, 320:3.79, 340:3.86, 360:3.92, 380:3.96, 400:3.99, 420:4.02, 440:4.08, 460:4.17, 
480:4.28, 500:4.41, 520:4.54, 540:4.65, 560:4.74, 580:4.79, 600:4.82 
} 

당신이 수를 가지고있다 ... :

import bisect 
teekeys = sorted(tee) 

def lookup(aval): 
    where = bisect.bisect_left(teekeys, aval) 
    lo = teekeys[where-1] 
    hi = teekeys[where] 
    if lo==hi: return tee[lo] 
    delta = float(aval-lo)/(hi-lo) 
    return delta*tee[hi] + (1-delta)*tee[lo] 
그래서 예를 들어

:

print(lookup(110)) 
2.955 
print(lookup(530)) 
4.595 

회원님이 값이 <min(tee) 또는 >max(tee) 인 경우 수행 할 작업을해야합니다 - 같은 변칙적 인 경우에 OK 예외를 발생한다?

+0

예, 예외를 발생시키는 것은 사전에 포함되지 않은 값에 대해서는 문제가되지 않습니다. 나는 이것이 잘 될 것이라고 생각한다. :-) 고맙습니다! 값이 정확하지 않으면 if 문을 추가하여 사용자 입력으로 조회 함수를 호출합니다. –