Skip to content

Instantly share code, notes, and snippets.

@BSVogler
Created September 4, 2017 18:44
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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.
#!/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