n00bprogrammer22
n00bprogrammer22

Reputation: 187

Navigating through a dictionary in Python

I have a dictionary called "locations". A function I'm writing for the dictionary is set up in the format (d, description, current) where 'd' references the dictionary, 'description' references a string describing the location we are looking for, and 'current' references the spot we currently are in the dictionary as a pair of coordinates (x,y).

Basically, each location has multiple positions in the dictionary each with its own pair of coordinates and my goal is to find the closest position to where we currently are in the dictionary (current). The strategy is to use the distance formula to calculate this.

For example if we were looking for the nearest gas station and we were currently at (2,2), the function should return (3,1) for the nearest station if the two stations were at (3,1) and (1,4) as (3,1) is closer to (2,2) Any advice on my current code would be appreciated.

Code:

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

My current code has no errors but is definitely not working correctly. It is just returning 0,0 and I'm not sure how I can fix it to return the coordinates of the closest location to our current position.

Upvotes: 1

Views: 1923

Answers (2)

Michael Currin
Michael Currin

Reputation: 680

After considering the comments, here is my solution.

#!/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
"""

Upvotes: 1

Michael Currin
Michael Currin

Reputation: 680

I think you need to use the dictionary input to calculate results for place names against their distance from the current location as a single float (or decimal).

Something like

current_location = (x, y)
distancesFromCurrent = [distanceFormula(z, current_location) for z in places]

Where distanceFormula would be using you distance calc in function.

Once you have that for all places inputted, then you can do another loop find the minimum float value in the dictionary and return its corresponding place name and its co-ordinate location (from the original input).

I think you could change from dictionary to list input to be in this format below. (if you have anything data like this already to show us that would help too)

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.
             ]

Then your function would have find the closest the location but first filter out the locations which have the feature which matches your description.

Hope that helps.

Upvotes: 0

Related Questions