Problem 2.1 : Distance (100pts)
Problem
We will now implement the function distance, which computes the distance between two city objects. Recall that the distance between two coordinate pairs
(x1, y1)and(x2, y2)can be found by calculating the sqrt of(x1 - x2)**2 + (y1 - y2)**2. We have already importedsqrtfor your convenience. Use the latitude and longitude of a city as its coordinates; you'll need to use the selectors to access this info!
我们现在将实现 distance 函数,它计算两个城市对象之间的距离。回想一下,两个坐标对 \((x_1, y_1)\) 和 \((x_2, y_2)\) 之间的距离可以通过计算 \(\sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}\) 得到。为了您的方便,我们已经导入了 sqrt。请使用城市的纬度和经度作为它的坐标;您需要使用选择函数来获取这些信息!
from math import sqrt
def distance(city1, city2):
"""
>>> city1 = make_city('city1', 0, 1)
>>> city2 = make_city('city2', 0, 2)
>>> distance(city1, city2)
1.0
>>> city3 = make_city('city3', 6.5, 12)
>>> city4 = make_city('city4', 2.5, 15)
>>> distance(city3, city4)
5.0
"""
"*** YOUR CODE HERE ***"
Hints
Hint: Though strange, but for convenience we assume that the earth is flat, and use the euclidean distance.
- 虽然很奇怪,但为了方便,我们假设地球是平的,并使用欧几里得距离(Euclidean distance)。
Solutions
注意不要打破抽象。
def distance(city1, city2):
return sqrt((get_lat(city1) - get_lat(city2)) ** 2 + (get_lon(city1) - get_lon(city2)) ** 2)