Practice problems: Lambda expressions
Easy
Question 1: Mul_by_num
Using a lambda
expression, complete the mul_by_num
function. This
function should take an argument and return a one argument function
that multiplies any value passed to it by the original number. Its
body must be one line long:
def mul_by_num(num):
"""
Returns a function that takes one argument and returns num
times that argument.
>>> x = mul_by_num(5)
>>> y = mul_by_num(2)
>>> x(3)
15
>>> y(-4)
-8
"""
"*** YOUR CODE HERE ***"
return ______
return lambda num2: num * num2
Medium
Question 2: Butch Cassidy and the Environment Diagram
Draw the environment diagram for the following code:
def blondie(f):
return lambda x: f(x + 1)
tuco = blondie(lambda x: x * x)
angel_eyes = tuco(2)
Question 3: Community
Fill in the blanks as to what Python would do here. Please try this problem first with an environment diagram, and then again without an environment diagram.
>>> def troy():
... abed = 0
... while abed < 10:
... britta = lambda: abed
... abed += 1
... abed = 20
... return britta
...
>>> jeff = troy()
>>> shirley = lambda : jeff
>>> pierce = shirley()
>>> pierce()
______20
Question 4
Fill in the blanks so that the doctests pass.
"""
>>> a()
2
>>> b(3)
1
>>> b(10)
1
>>> b(2)
1
>>> c(1)
1
>>> c(3)
3
>>> d(1, 3)
4
>>> d(2, 5)
7
>>> e(1, 3)
3
>>> e(2, 5)
5
>>> f(2, 5)
52
>>> f(3, 1)
13
>>> g(1)(2)
12
>>> g(2)(1)
21
>>> h()(2)
7
>>> h()(3)
8
>>> i(2, 5)(2)
4
>>> i(3, 5)(2)
5
>>> j(lambda x: 2)(1)
2
>>> j(lambda x: x + 1)(1)
2
>>> (lambda x: x(2))(k)
3
>>> (lambda x: lambda y: x(y()))(m)(n)
5
>>> o('cal')
cal
>>> p(lambda x: x + 2, lambda x: x + 3)(1)
6
>>> q('veggies')(lambda: 'eat')
eat veggies
>>> happy = r(30, lambda: new_year() // 1000)
>>> new_year = (lambda x: lambda: x)(2000)
>>> happy(new_year)
2015
>>> s(lambda x: x()('cal'))
cal
>>> t('ta')('n')
arctan
>>> u('sine')
arccosine
>>> v()
arccosecant
"""
a = _______
b = _______
c = _______
d = _______
e = _______
f = _______
g = _______
h = _______
i = _______
j = _______
k = _______
# There is no l
m = _______
n = _______
o = _______
p = _______
q = _______
r = _______
s = _______
def t(__):
_________________
def u(__): # use t!
_________________
def v():
_________________
a = lambda: 2
b = lambda x: 1
c = lambda x: x
d = lambda x, y: x + y
e = lambda x, y: y
f = lambda x, y: y * 10 + x
g = lambda x: lambda y: 10 * x + y
h = lambda: lambda x: x + 5
i = lambda x, y: lambda z: x + z
j = lambda x: lambda y: x(y)
k = lambda x: x + 1
# There is no l
m = lambda x: x
n = lambda: 5
o = lambda x: print(x)
p = lambda x, y: lambda z: x(y(z))
q = lambda x: lambda y: print(y(), x)
r = lambda x, y: lambda z: z() + x // y()
s = lambda x: x(lambda: print)
def t(x):
return lambda y: print('arc' + x + y)
def u(x): # use t!
return t('co' + x)('')
def v():
return u('secant')