Before you turn this problem in, make sure everything runs as expected. First, restart the kernel (in the menubar, select Kernel$\rightarrow$Restart) and then run all cells (in the menubar, select Cell$\rightarrow$Run All).

Make sure you fill in any place that says YOUR CODE HERE or "YOUR ANSWER HERE", as well as your name and collaborators below:

In [ ]:
NAME = ""
COLLABORATORS = ""

In [ ]:
import os
import os.path
import random

Functions as Objects

In [ ]:
def add1(n):
    return n+1
In [ ]:
L1 = [ random.randint(1,30) for i in range(5) ]

L2 = []
for val in L1:
    newval = add1(val)
    L2.append(newval)

print(L1)
print(L2)
In [ ]:
def apply_func(func, data):
    result = []
    for val in data:
        newval = func(val)
        result.append(newval)
    return result
In [ ]:
L2 = apply_func(add1, L1)
print(L2)

Q Create three more functions, add2, add3, and add4 and then create a list called funcs whose elements are the four functions add1 through add4.

In [ ]:
# YOUR CODE HERE
raise NotImplementedError()

Q Suppose you are given a list of numbers L3 whose length is the same as funcs. Write code to generate list L4 whose values come from applying the corresponding function from funcs to its correspondent in L3. Bonus to do this with a list comprehension.

In [ ]:
L3 = [5, 9, 2, 7]
# YOUR CODE HERE
raise NotImplementedError()
print(L4)

Lambda Functions

In [ ]:
lambda x: x+1
In [ ]:
lambda x, y: x/y * 2
In [ ]:
lambda x, y: x/y * 2 if y != 0 else 999999
In [ ]:
lambda L: [ abs(x) for x in L ]
In [ ]:
lambda L: [ abs(x) if x % 2 == 0 else x - 1 for x in L ]