Skip to content

Instantly share code, notes, and snippets.

@ekohilas
Created November 5, 2016 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekohilas/e1fcbce28cab367c8f4b5853355ec21f to your computer and use it in GitHub Desktop.
Save ekohilas/e1fcbce28cab367c8f4b5853355ec21f to your computer and use it in GitHub Desktop.
Tutorial week 12 question 5
from os import scandir
from sys import argv
from math import radians, cos, sin, asin, sqrt
def iterate_users(dataset_path):
l = []
for user in scandir(dataset_path):
for f in scandir(user.path):
if f.name == "user.txt":
l.append(parse_file(f.path))
return l
def parse_file(filename):
my_lat, my_lon = -33.9172238, 151.2302268
d = {}
for line in open(filename):
name, data = line.strip().split("=", 1)
d[name] = data
d["distance"] = haversine(float(d.get("home_longitude", 0)), float(d.get("home_latitude", 0)), my_lon, my_lat)
return d
for user in sorted(iterate_users(argv[1]), key = lambda x: x["distance"]):
if user["distance"]:
print("{} lives at {} {} in {}".format(user["zid"], user["home_latitude"], user["home_longitude"], user["home_suburb"]))
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
if lon1 and lat1:
return c * r
else:
return 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment