def flatten(s):
"""Returns a flattened version of list s.
>>> flatten([1, 2, 3]) # normal list
[1, 2, 3]
>>> x = [1, [2, 3], 4] # deep list
>>> flatten(x)
[1, 2, 3, 4]
>>> x # Ensure x is not mutated
[1, [2, 3], 4]
>>> x = [[1, [1, 1]], 1, [1, 1]] # deep list
>>> flatten(x)
[1, 1, 1, 1, 1, 1]
>>> x
[[1, [1, 1]], 1, [1, 1]]
>>> x = [[1, [2, 3], [4, [5, 6]]]]
>>> flatten(x)
[1, 2, 3, 4, 5, 6]
>>> x
[[1, [2, 3], [4, [5, 6]]]]
>>> x = [[1, [1, [1, [1, 1, [1, 1, [1]]]], 1]]]
>>> flatten(x)
[1, 1, 1, 1, 1, 1, 1, 1, 1]
>>> x
[[1, [1, [1, [1, 1, [1, 1, [1]]]], 1]]]
"""
"*** YOUR CODE HERE ***"
res = []
for i in s:
if type(i) == list:
res += flatten(i)
else:
res += [i]
return res
def my_map(fn, seq):
"""Applies fn onto each element in seq and returns a list.
>>> my_map(lambda x: x*x, [1, 2, 3])
[1, 4, 9]
>>> my_map(lambda x: abs(x), [1, -1, 5, 3, 0])
[1, 1, 5, 3, 0]
>>> my_map(lambda x: print(x), ['cs61a', 'spring', '2023'])
cs61a
spring
2023
[None, None, None]
"""
return [fn(i) for i in seq]
def my_filter(pred, seq):
"""Keeps elements in seq only if they satisfy pred.
>>> my_filter(lambda x: x % 2 == 0, [1, 2, 3, 4]) # new list has only even-valued elements
[2, 4]
>>> my_filter(lambda x: (x + 5) % 3 == 0, [1, 2, 3, 4, 5])
[1, 4]
>>> my_filter(lambda x: print(x), [1, 2, 3, 4, 5])
1
2
3
4
5
[]
>>> my_filter(lambda x: max(5, x) == 5, [1, 2, 3, 4, 5, 6, 7])
[1, 2, 3, 4, 5]
"""
return [i for i in seq if pred(i)]
def my_reduce(combiner, seq):
"""Combines elements in seq using combiner.
seq will have at least one element.
>>> my_reduce(lambda x, y: x + y, [1, 2, 3, 4]) # 1 + 2 + 3 + 4
10
>>> my_reduce(lambda x, y: x * y, [1, 2, 3, 4]) # 1 * 2 * 3 * 4
24
>>> my_reduce(lambda x, y: x * y, [4])
4
>>> my_reduce(lambda x, y: x + 2 * y, [1, 2, 3]) # (1 + 2 * 2) + 2 * 3
11
"""
"*** YOUR CODE HERE ***"
res = seq[0]
for i in range(1, len(seq)):
res = combiner(res, seq[i])
return res
def my_map_syntax_check():
"""Check that your two_of_three code consists of nothing but a return statement.
>>> # You aren't expected to understand the code of this test.
>>> import inspect, ast
>>> [type(x).__name__ for x in ast.parse(inspect.getsource(my_map)).body[0].body]
['Expr', 'Return']
"""
# You don't need to edit this function. It's just here to check your work.
def my_filter_syntax_check():
"""Check that your two_of_three code consists of nothing but a return statement.
>>> # You aren't expected to understand the code of this test.
>>> import inspect, ast
>>> [type(x).__name__ for x in ast.parse(inspect.getsource(my_filter)).body[0].body]
['Expr', 'Return']
"""
# You don't need to edit this function. It's just here to check your work.
from math import sqrt
def distance(city_a, city_b):
"""
>>> city_a = make_city('city_a', 0, 1)
>>> city_b = make_city('city_b', 0, 2)
>>> distance(city_a, city_b)
1.0
>>> city_c = make_city('city_c', 6.5, 12)
>>> city_d = make_city('city_d', 2.5, 15)
>>> distance(city_c, city_d)
5.0
"""
"*** YOUR CODE HERE ***"
return sqrt((get_lat(city_a) - get_lat(city_b)) ** 2 + (get_lon(city_a) - get_lon(city_b)) ** 2)
def closer_city(lat, lon, city_a, city_b):
"""
Returns the name of either city_a or city_b, whichever is closest to
coordinate (lat, lon). If the two cities are the same distance away
from the coordinate, consider city_b to be the closer city.
>>> 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 ***"
coord = make_city('Coord', lat, lon)
if distance(city_a, coord) < distance(city_b, coord):
return get_name(city_a)
else:
return get_name(city_b)
def check_city_abstraction():
"""
There's nothing for you to do for this function, it's just here for the extra doctest
>>> change_abstraction(True)
>>> city_a = make_city('city_a', 0, 1)
>>> city_b = make_city('city_b', 0, 2)
>>> distance(city_a, city_b)
1.0
>>> city_c = make_city('city_c', 6.5, 12)
>>> city_d = make_city('city_d', 2.5, 15)
>>> distance(city_c, city_d)
5.0
>>> 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'
>>> change_abstraction(False)
"""
# Treat all the following code as being behind an abstraction layer,
# you shouldn't need to look at it.
def make_city(name, lat, lon):
"""
>>> city = make_city('Berkeley', 0, 1)
>>> get_name(city)
'Berkeley'
>>> get_lat(city)
0
>>> get_lon(city)
1
"""
if change_abstraction.changed:
return {"name": name, "lat": lat, "lon": lon}
else:
return [name, lat, lon]
def get_name(city):
"""
>>> city = make_city('Berkeley', 0, 1)
>>> get_name(city)
'Berkeley'
"""
if change_abstraction.changed:
return city["name"]
else:
return city[0]
def get_lat(city):
"""
>>> city = make_city('Berkeley', 0, 1)
>>> get_lat(city)
0
"""
if change_abstraction.changed:
return city["lat"]
else:
return city[1]
def get_lon(city):
"""
>>> city = make_city('Berkeley', 0, 1)
>>> get_lon(city)
1
"""
if change_abstraction.changed:
return city["lon"]
else:
return city[2]
###############
from functools import reduce
def count_palindromes(L):
"""The number of palindromic words in the sequence of strings
L (ignoring case).
>>> count_palindromes(("Acme", "Madam", "Pivot", "Pip"))
2
"""
return reduce(lambda cnt, s: cnt + 1 if s == s[::-1] else cnt, map(str.lower, L), 0)
def coords(fn, seq, lower, upper):
"""
>>> seq = [-4, -2, 0, 1, 3]
>>> fn = lambda x: x**2
>>> coords(fn, seq, 1, 9)
[[-2, 4], [1, 1], [3, 9]]
"""
"*** YOUR CODE HERE ***"
return [[i, fn(i)] for i in seq if fn(i) >= lower and fn(i) <= upper]
def change_abstraction(change):
"""
For testing purposes.
>>> change_abstraction(True)
>>> change_abstraction.changed
True
"""
change_abstraction.changed = change
change_abstraction.changed = False
CS61A Spring 2023 Lab 05
于 2024-05-17 23:04:18 首次发布