lab6-extra

The eval_f exercise implements a command that is already available in Python (map). By implementing it yourself, you may understand much better what it does, and when to use map().

eval_f(f, xs)

Write a function eval_f(f, xs) which takes a function f=f(x) and a list xs of values that should be used as arguments for f. The function eval_f should apply the function f subsequently to every value x in xs, and return a list fs of function values. I.e. for an input argument xs=[x0, x1, x2, ..., xn] the function call eval_f(f, xs) should return [f(x0), f(x1), f(x2), ..., f(xn)].

Example 1:

In [ ]: def square(x):
   ...:     return x * x
   ...:

In [ ]: eval_f(square, [-1, 10, 20, 42])
Out[ ]: [1, 100, 400, 1764]

Example 2:

In [ ]: import math

In [ ]: eval_f(math.sqrt, [1, 2, 4, 9])
Out[ ]: [1.0, 1.4142135623730951, 2.0, 3.0]

Example 3:

In [ ]: def sign(x):
    ...:     if x > 0:
    ...:         return 1
    ...:     elif x < 0:
    ...:         return -1
    ...:     else:
    ...:         return 0
    ...:

In [ ]: sign(-1.1)
Out[ ]: -1

In [ ]: sign(0.1)
Out[ ]: 1

In [ ]: sign(0.0)
Out[ ]: 0

In [ ]: eval_f(sign, [-0.2, -0.1, 0, 0.1, 0.2, 0.3])
Out[ ]: [-1, -1, 0, 1, 1, 1]

Please include the extra tasks in your file lab6.py and submit as Computing lab6 assignment.

Back to lab6.

End of lab6-extra.