Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- import json
- import numpy as np
- import unittest
- # constants
- FILENAME = 'customers.json'
- INTERCOM_COORDS = [53.339428,-6.257664]
- WITHIN_DISTANCE = 100
- EARTH_RADIUS = 6367
- def read_file_as_json(filename):
- """reads a json file and returns an object"""
- with open(filename, 'r') as json_file:
- data = json.load(json_file)
- return data
- def haversine(coord1, coord2):
- """calculates the great-circle distance between two coordinates using haversine formula and
- returns the distance in km."""
- lat1, lon1 = map(np.deg2rad, coord1)
- lat2, lon2 = map(np.deg2rad, coord2)
- delta_lat = abs(lat2 - lat1)
- delta_lon = abs(lon2 - lon1)
- a = np.sin(delta_lat / 2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(delta_lon / 2.0)**2
- central_angle = 2 * np.arcsin(np.sqrt(a))
- distance = EARTH_RADIUS * central_angle
- return distance
- def in_distance(coord1, coord2, distance):
- """checks whether two coordinates within a given distance"""
- return haversine(coord1, coord2) <= distance
- def customer_coords(customer):
- """returns a list containing longitude and latitude of given customer"""
- return map(float, [customer['latitude'], customer['longitude']])
- def customers_in_distance(customers):
- """returns the names and user ids of customers within 100km, sorted by User ID"""
- customers = [(c['name'], c['user_id']) for c in customers if in_distance(INTERCOM_COORDS, customer_coords(c), WITHIN_DISTANCE)]
- customers = sorted(customers, key=lambda tup: tup[1])
- return customers
- def print_customers(customers):
- """prints names and user ids of customers within 100 km from Intercom office."""
- for customer in customers:
- print "{0} - {1}".format(customer[0], customer[1])
- class TestCustomers(unittest.TestCase):
- def setUp(self):
- self.json = read_file_as_json(FILENAME)
- def test_read_file_as_json(self):
- self.assertEqual(len(self.json), 32)
- def test_haversine(self):
- self.assertEqual(haversine([0,0], [0,0]), 0)
- self.assertEqual(int(haversine(INTERCOM_COORDS, [51.92893,-10.27699])), 313)
- def test_in_distance(self):
- self.assertEqual(in_distance([0,0], [0,0], 0), True)
- self.assertEqual(in_distance(INTERCOM_COORDS, [51.92893,-10.27699], WITHIN_DISTANCE), False)
- def test_customer_coords(self):
- first_customer_coords = customer_coords(self.json[0])
- self.assertEqual(first_customer_coords, [52.986375, -6.043701])
- def test_customers_in_distance(self):
- customers = customers_in_distance(self.json)
- self.assertEqual(len(customers), 16)
- def test_print_customers(self):
- customers = customers_in_distance(self.json)
- print '\n'
- print_customers(customers)
- if __name__ == "__main__":
- unittest.main()
Add Comment
Please, Sign In to add comment