Jul-14-2020, 05:27 AM
Hello,
So to practice functionality, I wrote out a calculator to determine the distance between two cities using the haversine formula. User inputs the cities name and coordinates.
So to practice functionality, I wrote out a calculator to determine the distance between two cities using the haversine formula. User inputs the cities name and coordinates.
import math def city_loc(): '''User inputs city name, and coordinates in NNN.NNNNN formant. Negative values for cities in the western and southern hemisphers.''' city_name = input('What is your first city? ') city_coordN = float(input('What is the north/south coordinate? ')) city_coordE = float(input('What is the east/west coordinates" ')) city_coord = (city_coordN,city_coordE,city_name) return tuple(city_coord) def curve_dist(city1,city2): '''Calculates the distance between two cities on Earth using the haversine method. Coordinates, in tuple form, are used and need to be in NNN.NNNNN formant. Negative values for cities in the western and southern hemisphers.''' delta_phi = (city1[0]-city2[0])*(math.pi/180) delta_lamda = (city1[1]-city2[1])*(math.pi/180) a = math.sin(delta_phi/2)**2+math.cos(city1[0]*(math.pi/180))*math.cos(city1[0]*(math.pi/180))*math.sin(delta_lamda/2)**2 c = 2 * math.atan2(a**.5,(1-a)**.5) return(6371 * c) #-----main program---------- print('Welcome to the city distance calculator, where we tell you the distance between cities as the crow flies in kilometers.') city1 = city_loc() city2 = city_loc() dist = curve_dist(city1,city2) print('The distance between {} and {} is {d:.2f} km'.format(city1[2],city2[2],d=dist))I am open to any comments on either efficiency improvements, corrections, or if the code documentation could be better. Next version could have unit conversion and possible a text list of multiple cities with their coordinates typed out in a txt file.