karan / Projects

:page_with_curl: A list of practical projects that anyone can solve in any programming language.
https://twitter.com/karangoel
MIT License
44.65k stars 10.53k forks source link

distance.py bug #17

Closed MrBlaise closed 10 years ago

MrBlaise commented 10 years ago

Hello!

I have found some bug in the distance.py file.

1.) It did not accept 'mi' as an input, only 'km' 2.) It would've always show the miles format (if unit == k) when unit is either 'km' or 'mi'

Fixed code

#!/usr/bin/env python

"""
Distance Between Two Cities - Calculates the distance between
two cities and allows the user to specify a unit of distance.
This program may require finding coordinates for the cities
like latitude and longitude.

Uses the Haversine formula
(http://www.movable-type.co.uk/scripts/latlong.html)

Dependencies:
geopy
    pip install geopy
"""

from geopy import geocoders # to find lat/lon for the city
import math

R = 6373 # km

city1 = raw_input('Enter city 1: ')
city2 = raw_input('Enter city 2: ')
unit = raw_input('Enter unit of distance (K = KM, M = MI): ').lower()

# BUG #1: if unit in 'km'
if unit == 'km' or unit == 'mi':

    g = geocoders.GoogleV3()

    try:
        city1, (lat1, lon1) = g.geocode(city1)
        city2, (lat2, lon2) = g.geocode(city2)
    except:
        raise Exception('Unable to locate the citites. Check the city names.')

    # convert decimal locations to radians
    lat1 = math.radians(lat1)
    lon1 = math.radians(lon1)
    lat2 = math.radians(lat2)
    lon2 = math.radians(lon2)

    # start haversne formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = (math.sin(dlat/2) ** 2) + math.cos(lat1) * math.cos(lat2) * \
    (math.sin(dlon/2) ** 2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
    d = R * c

    # BUG #2: if unit == 'k' 
    if unit == 'km':
        print 'Distance between %s and %s is %.04f km' % (city1, city2, d)
    else:
        print 'Distance between %s and %s is %.04f mi' % (city1, city2, d / 1.60934)
else:
    print 'Invalid unit input!'
karan commented 10 years ago

Well so:

unit = raw_input('Enter unit of distance (K = KM, M = MI): ').lower()

The text K = KM, M = MI instructs user to enter k for km and m for mi. By that logic, the code works perfectly fine!

MrBlaise commented 10 years ago

That's true sorry about that! However it might be more user-friendly with 'km' the and 'mi' but that is just me :)

karan commented 10 years ago

I've updated the instructions for the user, but the logic is otherwise fine! :-)