If you need help reviewing Map, filter, and friends, take a look at these resources:
Each question has a "Toggle Solution" button -- click it to reveal that question's solution.
What would Python print?
Question 1
>>> tup = (1, 2, 3, 4, 5)
>>> map(lambda x: x*2, tup)
______<map object ...>
>>> tuple(map(lambda x: x*2, tup))
______(2, 4, 6, 8, 10)
>>> tup
______(1, 2, 3, 4, 5)
>>> tuple(map(lambda x: 3, tup))
______(3, 3, 3, 3, 3)
Question 2
>>> tup = (1, 2, 3, 4, 5)
>>> filter(lambda x: x % 2 == 0, tup)
______<filter object>
>>> tuple(filter(lambda x: x % 2 == 0, tup))
______(2, 4)
>>> tup
______(1, 2, 3, 4, 5)
>>> tuple(filter(lambda x: False, tup))
______()
Question 3
>>> from functools import reduce
>>> tup = (1, 2, 3, 4, 5)
>>> reduce(lambda x, y: x + y, tup)
______15
>>> reduce(lambda x: x**2, tup)
______TypeError
Code-Writing questions
Question 4
Implement a function map
that acts just like the built-in map
,
except that it returns a tuple instead of a map object.
def map(f, seq):
"""Acts just like the built-in map function, but returns a
tuple.
>>> tup = (1, 2, 3, 4)
>>> map(lambda x: x**2, tup)
(1, 4, 9, 16)
"""
"*** YOUR CODE HERE ***"
def map(f, seq):
tup = ()
for elem in seq:
tup += (f(elem),)
return tup
Question 5
Implement a function filter
that acts just like the built-in
filter
, except that it returns a tuple instead of a filter object.
def filter(pred, seq):
"""Acts just like the built-in filter function, but returns a
tuple.
>>> seq = range(10)
>>> filter(lambda x: x % 2 == 0, seq)
(0, 2, 4, 6, 8)
"""
"*** YOUR CODE HERE ***"
def filter(pred, seq):
tup = ()
for elem in seq:
if pred(elem):
tup += (elem,)
return tup
Question 6
Implement a function reduce
that acts just like the built-in
reduce
.
def reduce(combiner, seq):
"""Acts just like the built-in reduce function.
>>> seq = (1, 2, 3, 4, 5, 6)
>>> reduce(lambda x, y: x + y, seq)
21
>>> reduce(lambda x, y: x * y, (1, 2, 3, 4))
24
"""
"*** YOUR CODE HERE ***"
def reduce(combiner, seq):
total = seq[0]
for elem in seq[1:]:
total = combiner(total, elem)
return total