Skip to content

Commit 462a07d

Browse files
author
Karan Goel
committed
Distance between cities done
1 parent eb5eb15 commit 462a07d

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Numbers/distance.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
Distance Between Two Cities - Calculates the distance between
5+
two cities and allows the user to specify a unit of distance.
6+
This program may require finding coordinates for the cities
7+
like latitude and longitude.
8+
9+
Uses the Haversine formula
10+
(http://www.movable-type.co.uk/scripts/latlong.html)
11+
12+
Dependencies:
13+
geopy
14+
pip install geopy
15+
"""
16+
17+
from geopy import geocoders # to find lat/lon for the city
18+
import math
19+
20+
R = 6373 # km
21+
22+
city1 = raw_input('Enter city 1: ')
23+
city2 = raw_input('Enter city 2: ')
24+
unit = raw_input('Enter unit of distance (K = KM, M = MI): ').lower()
25+
26+
if unit in 'km':
27+
28+
g = geocoders.GoogleV3()
29+
30+
try:
31+
city1, (lat1, lon1) = g.geocode(city1)
32+
city2, (lat2, lon2) = g.geocode(city2)
33+
except:
34+
raise Exception('Unable to locate the citites. Check the city names.')
35+
36+
# convert decimal locations to radians
37+
lat1 = math.radians(lat1)
38+
lon1 = math.radians(lon1)
39+
lat2 = math.radians(lat2)
40+
lon2 = math.radians(lon2)
41+
42+
# start haversne formula
43+
dlon = lon2 - lon1
44+
dlat = lat2 - lat1
45+
a = (math.sin(dlat/2) ** 2) + math.cos(lat1) * math.cos(lat2) * \
46+
(math.sin(dlon/2) ** 2)
47+
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
48+
d = R * c
49+
50+
if unit == 'k':
51+
print 'Distance between %s and %s is %.04f km' % (city1, city2, d)
52+
else:
53+
print 'Distance between %s and %s is %.04f mi' % (city1, city2, d / 1.60934)
54+
else:
55+
print 'Invalid unit input!'

0 commit comments

Comments
 (0)