n00bprogrammer22 - 1 year ago 99
Python Question

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

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
"""
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download