Practice problems: Higher Order Functions
Easy
Question 1
Draw an environment diagram for the following code:
>>> def adder_maker(x):
... def adder(y):
... return x + y
... return adder
>>> add3 = adder_maker(3)
>>> add3(4)
______7
>>> sub5 = adder_maker(-5)
>>> sub5(6)
______1
>>> sub5(10) == add3(2)
______True
Question 2
Draw the environment diagram for the following piece of code
def yak(zebra):
return 20 // zebra
def llama(alpaca):
zebra = 0
def yak(zebra):
return alpaca(zebra)
return yak
llama(yak)(4)
Medium
Question 3
>>> def troy():
... abed = 0
... while abed < 10:
... def britta():
... return abed
... abed += 1
... abed = 20
... return britta
>>> annie = troy()
>>> def shirley():
... return annie
>>> pierce = shirley()
>>> pierce()
______20
Question 4
Consider the following implementations of count_factors
and count_primes
:
def count_factors(n):
"""Return the number of positive factors that n has."""
i, count = 1, 0
while i <= n:
if n % i == 0:
count += 1
i += 1
return count
def count_primes(n):
"""Return the number of prime numbers up to and including n."""
i, count = 1, 0
while i <= n:
if is_prime(i):
count += 1
i += 1
return count
def is_prime(n):
if n < 2:
return False
i = 2
while i < n:
if n % i == 0:
return False
i += 1
return True
Generalize this logic by writing a function count_cond
, which takes in a
two-argument predicate function cond(n, i)
. count_cond
returns a
one-argument function that counts all the numbers from 1 to n
that satisfy
cond
.
def count_cond(condition):
"""
>>> count_factors = count_cond(lambda n, i: n % i)
>>> count_factors(2)
2
>>> count_factors(4)
3
>>> count_factors(12)
6
>>> count_primes = count_cond(lambda n, i: is_prime(i))
>>> count_primes(2)
1
>>> count_primes(3)
2
>>> count_primes(4)
2
>>> count_primes(5)
3
>>> count_primes(30)
10
"""
# BEGIN SOLUTION
def counter(n):
i, count = 1, 0
while i <= n:
if condition(n, i):
count += 1
i += 1
return count
return counter
# BEGIN SOLUTION
def is_prime(n):
if n < 2:
return False
i = 2
while i < n:
if n % i == 0:
return False
i += 1
return True
Question 5: Doge
Draw the following environment diagram:
wow = 6
def much(wow):
if much == wow:
such = lambda wow: 5
def wow():
return such
return wow
such = lambda wow: 4
return wow()
wow = much(much(much))(wow)