Skip to content

Instantly share code, notes, and snippets.

@sanandrea
Created January 12, 2016 17:21
Show Gist options
  • Save sanandrea/3c9cc470338d0190a871 to your computer and use it in GitHub Desktop.
Save sanandrea/3c9cc470338d0190a871 to your computer and use it in GitHub Desktop.
import json
from math import radians, cos, sin, acos, sqrt, pi
DUBLIN_HQ = {"lat" : 53.3381985,
"lon" : -6.2592576}
EARTH_RADIUS = 6371 #km
FILTER_RADIUS = 100 #km
#two points, expected result, floating error epsilon
DISTANCES = [
([{"lat" : 0,"lon" : 0}, {"lat" : 0,"lon" : 180}] , pi * EARTH_RADIUS , 0.0001)
#...
]
def read_customers(fname):
result = []
try:
with open(fname) as f:
content = f.readlines()
for i,line in enumerate(content):
result.append(json.loads(line))
except IOError:
print 'cannot open', fname
except:
print 'generic error'
return result
def read_customers_test():
if len(read_customers('customers.json')) == 0:
return False
if len(read_customers('custmers.json')) != 0:
return False
if len(read_customers(1)) != 0:
return False
print ()
return True
def haversine_distance(point_a,point_b):
#convert to radians
lon1, lat1, lon2, lat2 = map(radians, [point_a['lon'], point_a['lat'], point_b['lon'], point_b['lat']])
delta_lon = lon2 - lon1
a = sin(lat1)*sin(lat2) + cos(lat1) * cos(lat2)*cos(delta_lon)
return acos(a) * EARTH_RADIUS #km
def haversine_distance_test():
for i,tup in enumerate(DISTANCES):
if haversine_distance(tup[0][0],tup[0][1]) - tup[1] > tup[2]:
print "not equal"
return False
return True
def is_near(customer):
c_point = {}
c_point['lat'] = float(customer['latitude'])
c_point['lon'] = float(customer['longitude'])
if haversine_distance(c_point, DUBLIN_HQ) < FILTER_RADIUS:
return True
return False
def filter_customers(customers,func):
return filter(lambda s: func(s), customers)
def invite():
customers = read_customers('customers.json')
#filter
near_customers = filter_customers(customers, is_near)
#sort by id
near_customers.sort(key=lambda x: x['user_id'], reverse=False)
for c in near_customers:
print c['name'],",",c['user_id']
if __name__ == "__main__":
#perform some tests here
print "TESTS:"
if read_customers_test() and haversine_distance_test():
print "All tests passed\n"
else:
print "Tests failed"
#run
invite()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment