Week 11: Exercises

1. Location Class

Write a class Location that represents a position on the Earth. The class should have an initializer that takes arguments 'lat' and 'long' representing a latitude and longitude in degrees. The initializer should check that the given latitude and longitude are valid, i.e. that -90 ≤ lat ≤ +90 and that ‑180 ≤ long ≤ +180. If that is not the case, it should raise an InvalidLocation exception, which is a custom exception type that you should define.

Your class should implement the magic method __eq__ so that two Locations with the same longitude and longitude will be considered equal. It should also implement the magic method __hash__, so that a Location may be used as a key in a set or dictionary.

Also, implement a magic method __sub__ that computes the shortest distance along the Earth's surface between two given locations. You may perform this calcluation using the Haversine formula:

Here φ1, φ2 are the latitude of points 1 and 2, and λ1, λ2 are the longitude of points 1 and 2. r is the radius of the sphere (i.e. the Earth); you may use the value r = 6371, which is the approximate radius of the Earth in km. Note that Python's functions math.sin and math.cos take an angle in radians, not degrees.

Finally, use your class to calculate the distance between Prague (lat = 50.0875°, long = 14.421389°) and Timbuktu (lat = 16.775833°, long = -3.009444°).