Lab 6 - Nonlocal, Mutability
Write 2 easy mutating functions.
Instructions: https://inst.eecs.berkeley.edu/~cs61a/su19/lab/lab06/
Solution: https://github.com/tomthestrom/cs61a/blob/master/lab/lab06/lab06.py
Q1: Make Adder Increasing
Write a function which takes in an integer n
and returns a one-argument function. This function should take in some value x
and return n + x
the first time it is called, similar to make_adder
. The second time it is called, however, it should return n + x + 1
, then n + x + 2
the third time, and so on
def make_adder_inc(n):
"""
>>> adder1 = make_adder_inc(5)
>>> adder2 = make_adder_inc(6)
>>> adder1(2)
7
>>> adder1(2) # 5 + 2 + 1
8
>>> adder1(10) # 5 + 10 + 2
17
>>> [adder1(x) for x in [1, 2, 3]]
[9, 11, 13]
>>> adder2(5)
11
"""
"*** YOUR CODE HERE ***"
Q1: Solution
def make_adder_inc(n):
"""
>>> adder1 = make_adder_inc(5)
>>> adder2 = make_adder_inc(6)
>>> adder1(2)
7
>>> adder1(2) # 5 + 2 + 1
8
>>> adder1(10) # 5 + 10 + 2
17
>>> [adder1(x) for x in [1, 2, 3]]
[9, 11, 13]
>>> adder2(5)
11
"""
"*** YOUR CODE HERE ***"
i = 0
def adder_inc(x):
nonlocal i
added_sum = n + x + i
i = i + 1
return added_sum
return adder_inc
Q2: Map
Write a function that takes a function and a list as inputs and maps the function on the given list - that is, it applies the function to every element of the list.
Be sure to mutate the original list. This function should not return anything.
def map(fn, lst):
"""Maps fn onto lst using mutation.
>>> original_list = [5, -1, 2, 0]
>>> map(lambda x: x * x, original_list)
>>> original_list
[25, 1, 4, 0]
"""
"*** YOUR CODE HERE ***"
Q2: Solution
def map(fn, lst):
"""Maps fn onto lst using mutation.
>>> original_list = [5, -1, 2, 0]
>>> map(lambda x: x * x, original_list)
>>> original_list
[25, 1, 4, 0]
"""
"*** YOUR CODE HERE ***"
for i in range (len(lst)):
lst[i] = fn(lst[i])
Last updated