Created
September 4, 2017 18:44
-
-
Save BSVogler/c20702d1acbe80f0b1f0dad774c83e3a to your computer and use it in GitHub Desktop.
Code using the google maps API to identify the best place to live if you need to travel often.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/python3 | |
import googlemaps | |
import numpy as np | |
from datetime import datetime | |
gmaps = googlemaps.Client(key='redacted insert your own key') | |
with open('./concertCities.txt') as f: | |
concertCities = f.read().splitlines() | |
with open('./homeCities.txt') as f: | |
homeCities = f.read().splitlines() | |
#now = datetime.now() | |
departuretime = datetime(2017, 9, 4, 22, 00, 19, 958753) | |
ranking=dict() | |
for homeCity in homeCities: | |
travelTimes = dict()#contains pair of time and amount | |
for concertCity in concertCities: | |
#to concert | |
if concertCity not in travelTimes: | |
try: | |
directions_result = gmaps.directions(concertCity, | |
homeCity, | |
mode="transit", | |
departure_time=departuretime, | |
alternatives=False) | |
traveltime=int(directions_result[0]['legs'][0]['duration']['value']) | |
if (traveltime<10800): #no more than 3 h | |
travelTimes[concertCity] = traveltime, 1#in seconds | |
print("From "+concertCity+": "+str(traveltime)) | |
else: | |
print("From "+concertCity+ " more than 3h:"+str(traveltime)) | |
except Exception as detail: | |
print("Error fetching "+concertCity+": "+str(detail)) | |
else: | |
#increase | |
print("Duplicate "+concertCity+", now: "+str(travelTimes[concertCity][1]+1)) | |
travelTimes[concertCity] = travelTimes[concertCity][0],travelTimes[concertCity][1]+1#in seconds | |
npTravelTimes = np.array(list(travelTimes.values())) | |
averageTime = np.average(npTravelTimes[:,0]*npTravelTimes[:,1]) | |
averageTime /= 3600 | |
ranking[homeCity]=averageTime | |
print("----------") | |
print('Average travel time for '+ homeCity + " is "+str(averageTime)+"h") | |
print("Done, sorting") | |
import operator | |
ranking = sorted(ranking.items(), key=operator.itemgetter(1)) | |
print(ranking) | |
print("=====") | |
print("First City: "+str(ranking[0])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment