Skip to content

Problem 2.2 : Closer City (100pts)

Problem

Next, implement closer_city, a function that takes a latitude, longitude, and two cities, and returns the name of the city that is relatively closer to the provided latitude and longitude.

You may only use the selectors and constructors introduced above and the distance function you just defined for this question.

接下来,实现 closer_city 函数,该函数接受一个纬度、一个经度以及两个城市对象,并返回相对更接近所提供的纬度和经度的那个城市的名称

您在本题中只能使用前面介绍的选择函数、构造函数以及您刚刚定义的 distance 函数。

def closer_city(lat, lon, city1, city2):
    """
    Returns the name of either city1 or city2, whichever is closest to
    coordinate (lat, lon).

    >>> berkeley = make_city('Berkeley', 37.87, 112.26)
    >>> stanford = make_city('Stanford', 34.05, 118.25)
    >>> closer_city(38.33, 121.44, berkeley, stanford)
    'Stanford'
    >>> bucharest = make_city('Bucharest', 44.43, 26.10)
    >>> vienna = make_city('Vienna', 48.20, 16.37)
    >>> closer_city(41.29, 174.78, bucharest, vienna)
    'Bucharest'
    """
    "*** YOUR CODE HERE ***"

Hints

  • 可以假想一个城市 city('Nanjing', lat, lon),然后分别计算距离。

Solutions

假想一个城市 c

def closer_city(lat, lon, city1, city2):
    c = make_city("", lat, lon)
    closer_city = city1 if distance(c, city1) < distance(c, city2) else city2
    return get_name(closer_city)