Lab Check-in 2: Lists and ADT
Check-in questions and answers will be available after lab solutions are released.
Trust the Abstraction
Q1: Cities
Recall the following question from last week's lab (feel free to pull up the assignment):
>>> 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"
Ask students the following:
1) On a high level, what did you do to solve this problem? Why did you use get_lat
and get_lon
instead of indexing into the list that contains the city's information? (or alternatively, if they used distance
, ask why they created a new city containing lat
and lon
)
- If the student answered #1 within one minute, move on to question 2. Otherwise, feel free to check the student off and move on:
2) Say we passed in lat
, lon
, and cities
, which is a list of cities, instead of city1
and city2
. How would you go about solving the question?
Solution: Keep track of a minimum distance with some variable smallest
, loop over the list, and calculate the distance between each city and the given lat
and lon
. If the distance is smaller than smallest
, then update smallest
to be the distance between the current city and lat
/lon
, and update another variable city_name
with the name associated with the current city. Then return city_name
at the end of the loop.
- If the student answered #2 within one minute, ask the following question. Otherwise, feel free to check the student off and move on:
3) How would you solve the same question (involving a list of cities) in one line?
return get_name(min(cities, key = lambda x: ((get_lon(x)-lon)**2 + (get_lat(x)-lat)**2)**0.5))