Skip to content

Instantly share code, notes, and snippets.

@tgross
Created February 21, 2012 02:09
Show Gist options
  • Save tgross/1873022 to your computer and use it in GitHub Desktop.
Save tgross/1873022 to your computer and use it in GitHub Desktop.
Redsnake trivia: speed of a swallow
import math
import string
from time import struct_time
import json
from requests import request
def get_geocoord(pt):
'''
Take the Web2.0y approach and get Google to do all the
hard geocoding work for us.
'''
geoapi_addr = 'http://maps.googleapis.com/maps/api/geocode/json'
geoapi_args = { 'sensor': 'false' }
geoapi_args['address'] = pt
response = request('GET', geoapi_addr, params=geoapi_args)
if response.ok:
result = json.loads(response.text)
latlng = result['results'][0]['geometry']['location']
return [latlng['lat'], latlng['lng']]
else:
print 'Aaaaaaaahhh!: ' + response
def calc_great_circle(pt1, pt2):
'''
Sphereical law of cosines formula
'''
lat1 = pt1[0]
long1 = pt1[1]
lat2 = pt2[0]
long2 = pt2[0]
ang = math.cos( math.sin(lat2) * math.sin(lat1) +
math.cos(lat2) * math.cos(lat1) * math.cos(long2 - long1) )
r = 6372.8 # avg radius of Earth in km
dist = r * math.radians(ang)
return dist
def what_is_the_airspeed_of_a_swallow(orig, dst, t, was_laden=False):
'''
Takes address or lat/long for each point, and a time as a time_struct
'''
pt1 = get_geocoord(orig)
pt2 = get_geocoord(dst)
dist = calc_great_circle(pt1, pt2)
elapsed = (t.tm_hour +
(t.tm_min / 60.0) +
(t.tm_sec / 3600.0))
airspeed = dist / elapsed
# because we know an unladen swallow's flight is at
# least two laden swallow's flights.
if was_laden:
airspeed = airspeed * 2
return 'Estimated airspeed: {0} km/h'.format(round(airspeed, 0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment