PYTHON ONLY! PLEASE FOLLOW DIRECTIONS! DIRECTIONS: import math import stdio impo
ID: 3829283 • Letter: P
Question
PYTHON ONLY! PLEASE FOLLOW DIRECTIONS!
DIRECTIONS:
import math
import stdio
import sys
class Location:
"""
Represents a location on Earth.
"""
def __init__(self, lat, lon):
"""
Constructs a new location given its latitude and longitude values.
"""
self._lat = ...
self._lon = ...
def distanceTo(self, other):
"""
Returns the great-circle distance between self and other.
"""
...
def __str__(self):
"""
Returns a string representation of self.
"""
...
# Test client [DO NOT EDIT]. Reads floats lat1, lon1, lat2, lon2 from command
# representing two locations on Earth, constructs two Location objects from
# them, and writes them along with the great-circle distance between the two.
def _main():
lat1, lon1, lat2, lon2 = map(float, sys.argv[1:])
loc1 = Location(lat1, lon1)
loc2 = Location(lat2, lon2)
stdio.writeln('loc1 = ' + str(loc1))
stdio.writeln('loc2 = ' + str(loc2))
stdio.writeln('d(loc1, loc2) = ' + str(loc1.distanceTo(loc2)))
if __name__ == '__main__':
_main()
Explanation / Answer
import math
import stdio
import sys
class Location:
"""
Represents a location on Earth.
"""
def __init__(self, lat, lon):
"""
Constructs a new location given its latitude and longitude values.
"""
self._lat = lat
self._lon = lon
def distanceTo(self, other):
"""
Returns the great-circle distance between self and other.
"""
# convert decimal degrees to radians
lat1 = self._lat
lat2 = other._lat
lon1 = self._lon
lon2 = other._lon
lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2])
# haversine 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.asin(math.sqrt(a))
km = 6360 * c
return km
def __str__(self):
"""
Returns a string representation of self.
"""
return "(" + "{0:.2f}".format(self._lat) + ", " + "{0:.2f}".format(self._lon) + ")"
# Test client [DO NOT EDIT]. Reads floats lat1, lon1, lat2, lon2 from command
# representing two locations on Earth, constructs two Location objects from
# them, and writes them along with the great-circle distance between the two.
def _main():
lat1, lon1, lat2, lon2 = map(float, sys.argv[1:])
loc1 = Location(lat1, lon1)
loc2 = Location(lat2, lon2)
print('loc1 = ' + str(loc1))
print('loc2 = ' + str(loc2))
print('d(loc1, loc2) = ' + str(loc1.distanceTo(loc2)))
stdio.writeln('loc1 = ' + str(loc1))
stdio.writeln('loc2 = ' + str(loc2))
stdio.writeln('d(loc1, loc2) = ' + str(loc1.distanceTo(loc2)))
if __name__ == '__main__':
_main()
#code link: https://paste.ee/p/1dHcT
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.