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
defmake_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
defmake_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 =0defadder_inc(x):nonlocal i added_sum = n + x + i i = i +1return added_sumreturn 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.
defmap(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
defmap(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 inrange (len(lst)): lst[i]=fn(lst[i])