lab6¶
This lab is focussed on passing a function object f to another function g. Function f
can then be called inside function g. This makes it possible to have generic algorithms g
— such as numerical integration— which can be applied to any function f by passing
that function f as an argument to g.
box_volume_UPS() exercises default arguments.
Relevant supplementary videos :
Relevant Socratica video:
positive_places(f, xs)¶
Write a function positive_places(f, xs) that takes as arguments some
function f and a list of numbers xs and returns a list of
those-and-only-those elements x of xs for which f(x) returns
a value strictly greater than zero.
Example 1:
In [ ]: def my_f(x):
...: return x ** 3
...:
In [ ]: positive_places(my_f, [1, 2, -1, -2, 3, 42, -9])
Out[ ]: [1, 2, 3, 42]
In [ ]: positive_places(my_f, [1, 2, 3, 4, 5])
Out[ ]: [1, 2, 3, 4, 5]
In [ ]: positive_places(my_f, [])
Out[ ]: []
In [ ]: positive_places(my_f, [-1, -2, -3, -4, -5])
Out[ ]: []
Example 2:
In [ ]: def f(x):
...: return 2 * x + 4
...:
In [ ]: positive_places(f, [10, 1, -3, -1.5, 0, 0.5])
Out[ ]: [10, 1, -1.5, 0, 0.5]
eval_f_0123(f)¶
Write a function eval_f_0123(f) that evaluates the function
f=f(x) at positions x=0, x=1, x=2 and
x=3. The function should return the list
[f(0), f(1), f(2), f(3)].
Example 1:
In [ ]: def square(x):
...: return x * x
...:
In [ ]: eval_f_0123(square)
Out[ ]: [0, 1, 4, 9]
Example 2:
In [ ]: def cubic(x):
...: return x ** 3
...:
In [ ]: eval_f_0123(cubic)
Out[ ]: [0, 1, 8, 27]
Example 3:
In [ ]: def stars(x):
...: return "*" * x
...:
In [ ]: eval_f_0123(stars)
Out[ ]: ['', '*', '**', '***']
sum_f(f, xs)¶
Implement a function sum_f(f, xs) that returns the sum of the
function values of f evaluated at values x0, x1, x2, …,
xn where xs=[x0, x1, x2, ..., xn].
Example 1:
In [ ]: def f(x):
...: return x
...:
In [ ]: sum_f(f, [1, 2, 3, 10])
Out[ ]: 16
Example 2:
In [ ]: def square(x):
...: return x * x
...:
In [ ]: sum_f(square, [1, 2, 3, 10])
Out[ ]: 114
box_volume_UPS(a, b, c)¶
Write a function box_volume_UPS(a, b, c) that returns the volume of
a box with edge lengths a, b and c. Inputs should be
provided in inch, and the output should be expressed in inch^3.
The standard dimensions of the UPS express box (small) in the US are
a=13 inch, b=11 inch and c=2 inch.
Your function should use these values for a, b and c unless
others are provided.
Examples:
In [ ]: box_volume_UPS()
Out[ ]: 286
In [ ]: box_volume_UPS(a=10, b=10, c=10)
Out[ ]: 1000
In [ ]: box_volume_UPS(c=5)
Out[ ]: 715
Please submit your file lab6.py for this assignment.
Additional (voluntary) tasks are available in lab6-extra.
End of lab6.