2016-11-06 3 views
1

"locations"という辞書があります。私が辞書に書いている関数は、(d、description、current)の形式で設定されています。 'd'は辞書を参照し、 'description'は探している場所を表す文字列を参照し、 'current'は私たちは現在、座標のペア(x​​、y)として辞書にあります。Pythonで辞書をナビゲートする

基本的には、それぞれの場所は座標の独自のペアで辞書それぞれで複数のポジションを持っていると私の目標は、私たちが現在の辞書(現在)のどこにいるかに最も近い位置を見つけることです。戦略は距離計算式を使用してこれを計算することです。例えば

我々は最寄りのガソリンスタンドを探していたと我々は(2,2)で、現在であれば2つのステーションが(3,1)であった場合、関数は最寄り駅のために(3,1)を返す必要がありますがと(3,1)が(2,2)に近い(1,4)私の現在のコードに関するアドバイスをいただければ幸いです。

コード:

def closest(d, description, current): 
    current_location = (x, y) 
    d = {(3,1):'gas', (1,4):'gas', (2,1):'food', (5,5):'food'} 
    distancesFromCurrent = [distanceFormula(z, current_location) for z in places] 
    for z in d: 
    if z < minimum float: 
     return z 

私の現在のコードはエラーがなく、間違いなく正常に動作していません。それはちょうど0を返しています。私は現在の位置に最も近い位置の座標を返すようにそれを修正できるかどうかはわかりません。

+0

変数に同じ名前の関数を与えていない...だけで固定ことを指摘して – Olian04

+0

おかげでそれは – n00bprogrammer22

+0

私は、問題が最も近い場所を見つけると思う追加したいです。どういうわけか私はそれを見つけるために説明文字列を使うはずですが、これがどのように行われるのかわからないと思います – n00bprogrammer22

答えて

1

コメントを検討した後、私の解決策です。

#!/usr/bin/env python2 
# -*- coding: utf-8 -*- 
""" 
Created on Sun Nov 6 21:42:22 2016 

@author: michaelcurrin 
""" 

import math 

def findDistance(A, B): 
    """ 
    In 2D space find the distance between two co-orinates is 
    known as Eucliciean distance. 
    Args 
     A: tuple or list of x and y co-ordinates 
      e.g. (1,2) e.g. [1,2] 
     B: as A. 
    Retuns 
     distance: float. Decimal value for shortest between A and B 
    """ 
    x = (A[0] - B[0]) 
    y = (A[1] - B[1]) 
    distance = math.sqrt(x**2 + y**2) # square root 

    # remove comment if you want to see this outputted 
    # print distance 

    return distance 


def GetClosestPlace(places, loc, feature): 
    """find shortest distance between current location and each locations 
    but only ones which have the desired feature""" 

    # add distance from current location to each location 
    for index in range(len(places)): 

     # only continue if feature exists at place 
     if feature in places[index]['features']: 

      # calculate 
      distance = findDistance(loc, 
            places[index]['location']) 
     else: 
      # this is to represent n/a for now as every location needs a distance 
      # for this version, so that it will not be chosen 
      distance = 1000 

      # add calculated distance to existing dictionary for location 
     places[index]['distance'] = distance  


    # find shortest distance and return details for that place 

    allDistances = [x['distance'] for x in places] 
    shortestDistance = min(allDistances) 

    for place in places: 
     if place['distance'] == shortestDistance: 
      return place 


placesList = [dict(name='foo',location=(0,3), features=['gas', 'food']), 
       dict(name='bar',location=(4,6), features=['food', 'hospital']), 
       dict(name='abc',location=(0,9), features=['gas','barber']), 
       dict(name='xyz',location=(2,2), features=['food','barber']) 
       ] 

currentLocation = (5,9) 
desiredFeature='food' 

closestPlace = GetClosestPlace(placesList, currentLocation, desiredFeature) 

print 'Current location: %s' % str(currentLocation) 
print 'Desired feature: %s ' % desiredFeature 
print 
print 'The closest place is...' 
print 'Name: %s' % closestPlace['name'] 
print 'Location %s' % str(closestPlace['location']) 
print 'Distance %f' % closestPlace['distance'] 
# join multiple features in the list with commas 
print 'Features: %s' % ', '.join(closestPlace['features']) 

""" 
OUTPUT 

Current location: (5, 9) 
Desired feature: food 

The closest place is... 
Name: bar 
Location (4, 6) 
Distance 3.162278 
Features: food, hospital 
""" 
+0

上記の私の2番目のバージョンでは、機能の欠陥を修正し、出力フォーマットを改善しました。私は場所のための別の例を加えました。 – MikeCPT

+0

あなたは私があなたに最高の答えを与えた大きな助けとなりました。私は今、1つのエラーが発生していると私はなぜわからない。それは、GetClosestPlaceの行45で、d [index] ['features']内のフィーチャーが の場合: KeyError:0.私はキーエラーを引き起こす原因がわかりません – n00bprogrammer22

+0

あなたがPython 3.xを私は2.7ですか?それは最初の行、print文、そしておそらくエラーが発生している行に影響しますか? – MikeCPT

0

辞書の入力を使用して、現在の場所からの距離に対する地名の結果を1つの浮動小数点(または小数点)として計算する必要があると思います。

distanceFormulaは、関数内で使用する距離CALCを使用することでしょう
current_location = (x, y) 
distancesFromCurrent = [distanceFormula(z, current_location) for z in places] 

よう

何か。

あなたは、入力されたすべての場所のために、あなたは別のループの辞書で最小 float値を見つけると、それに対応する地名と(元の入力から)その座標位置を返す操作を行うことができたら。

辞書からリスト入力に変更すると、以下のようになります。 (あなたはすでにこのように何もデータを持っている場合は、あまりにも役立つだろうと私たちを見るために)

placesList = [dict(name='abc',location=(0,3), features=['gas station','mall', 'police dept', 'fire dept']), 
       dict(name='xyz',location=(4,5), features=['police dept', 'hospital']), 
      #etc. 
      ] 

その後、あなたの機能はあなたの記述と一致する機能を持っている場所から最も近い場所が、第一のフィルタを見つけなければなりません。

希望に役立ちます。

+0

私はまだ本当に混乱しています。 zは記述文字列と等しいか?最寄りの場所に常に最小浮動小数点値がありますか?特定の記述がある場所の最小浮動小数点値をどのくらい正確に検索するのですか?最も近いもの({(3,1): 'ガス'、(1,4): 'ガス'、(2,1): '食品'の説明に役立つものがあれば、 、(5,5): 'food'}、 'food'、(1,4))==(2,1)。 – n00bprogrammer22

+0

私はzを座標として使用しました。 (1,4)、記述ではない。 – MikeCPT

+0

ああ、私は地名が都市と町だと思った。それはまったくユーザーのためのラベルとして重要なのですか、それともコーディネートのサービスとの調整のみですか? – MikeCPT