Calculate the Haversine Distance around the earth in order to help Santa:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#!/usr/bin/env python # Haversine formula example in Python # Author: Wayne Dyck import math def distance(origin, destination): lat1, lon1 = origin lat2, lon2 = destination radius = 6371 # km dlat = math.radians(lat2-lat1) dlon = math.radians(lon2-lon1) a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \ * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) d = radius * c return d |

Python script to direct the reindeer and the sled:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
north_pole = (90,0) weight_limit = 1000 sleigh_weight = 10 import pandas as pd import numpy as np from haversine import distance def weighted_trip_length(stops, weights): tuples = [tuple(x) for x in stops.values] # adding the last trip back to north pole, with just the sleigh weight tuples.append(north_pole) weights.append(sleigh_weight) dist = 0.0 prev_stop = north_pole prev_weight = sum(weights) for i in range(len(tuples)): dist = dist + distance(tuples[i], prev_stop) * prev_weight prev_stop = tuples[i] prev_weight = prev_weight - weights[i] return dist def weighted_reindeer_weariness(all_trips): uniq_trips = all_trips.TripId.unique() if any(all_trips.groupby('TripId').Weight.sum() + sleigh_weight > weight_limit): raise Exception("One of the sleighs over weight limit!") dist = 0.0 for t in uniq_trips: this_trip = all_trips[all_trips.TripId==t] dist = dist + weighted_trip_length(this_trip[['Latitude','Longitude']], this_trip.Weight.tolist()) return dist gifts = pd.read_csv('gifts.csv') sample_sub = pd.read_csv('sample_submission.csv') all_trips = sample_sub.merge(gifts, on='GiftId') print(weighted_reindeer_weariness(all_trips)) |