I'm solving exercise 3 from lecture 3 of Berkeley's CS 61A (2012):
Fill in the definition of
map_tuple
.map_tuple
takes in a function and a tuple as arguments and applies the function to each element of the tuple.def map_tuple(func, tup): """Applies func to each element of tup and returns a new tuple. >>> a = (1, 2, 3, 4) >>> func = lambda x: x * x >>> map_tuple(func, a) (1, 4, 9, 16) """
I know that Python has a built-in map
function, but at this point in the course, the only operations on tuples that we have studied are indexing [1]
[-1]
, slicing [1:]
, and concatenation +
, so my solution needs to restrict itself accordingly.
My solution 1:
def map_tuple(func, tup):
"""Applies func to each element of tup and returns a new tuple.
>>> a = (1, 2, 3, 4)
>>> func = lambda x: x * x
>>> map_tuple(func, a)
(1, 4, 9, 16)
"""
length = len(tup)
count = 0
new_tuple = ()
while count < length:
new_tuple = new_tuple + (func(tup[count]),)
count = count + 1
return new_tuple
My solution 2:
def map_tuple_recursive(func, tup):
"""Applies func to each element of tup and returns a new tuple.
>>> a = (1, 2, 3, 4)
>>> func = lambda x: x * x
>>> map_tuple(func, a)
(1, 4, 9, 16)
"""
length = len(tup)
def new_tuple(count):
if count == length:
return ()
else:
return (func(tup[count]), ) + new_tuple(count + 1)
return new_tuple(0)
How can these solutions be improved?
tuple(map(func, tup))
? \$\endgroup\$+
,,
and slicing amidst usage of tuples \$\endgroup\$count = count + 1
). Neither solution uses really uses the operations you mentioned (except the obligatorytup[count]
). \$\endgroup\$