First-Class Functions · Practice
Quiz & exercises
Answer each question to see the explanation. Your best score is saved in this browser.
Quiz
Coding exercises
Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.
Exercise 1: Sort names by surname ✓ Passed
Write sort_names(names) that takes a list of 'First Last' strings and returns a new list sorted by surname, and by first name when surnames are equal. The comparison must be case-insensitive.
For example, ['ada Lovelace', 'Alan Turing', 'Grace Hopper', 'Bob lovelace'] becomes ['Grace Hopper', 'ada Lovelace', 'Bob lovelace', 'Alan Turing'].
def sort_names(names):
return sorted(names)
def test_by_surname():
"""sorts by surname"""
result = sort_names(['Alan Turing', 'Grace Hopper', 'Ada Lovelace'])
assert result == ['Grace Hopper', 'Ada Lovelace', 'Alan Turing'], f"got {result}"
def test_tie_break():
"""breaks surname ties by first name"""
result = sort_names(['Zoe Smith', 'Adam Smith', 'Bob Jones'])
assert result == ['Bob Jones', 'Adam Smith', 'Zoe Smith'], f"got {result}"
def test_case_insensitive():
"""ignores case"""
result = sort_names(['ada Lovelace', 'Alan Turing', 'Grace Hopper', 'Bob lovelace'])
assert result == ['Grace Hopper', 'ada Lovelace', 'Bob lovelace', 'Alan Turing'], f"got {result}"
def test_new_list():
"""does not modify the input list"""
names = ['Bob Jones', 'Adam Smith', 'Al Brown']
sort_names(names)
assert names == ['Bob Jones', 'Adam Smith', 'Al Brown'], "the input list was changed"
Hints (3)
sorted(names, key=...)returns a new list. The key function receives one full name.- Return a tuple
(surname, first_name)from the key, so ties on the surname are broken by the first name. - Lower-case (or
casefold()) the name inside the key to make the comparison case-insensitive.
Show a solution
def sort_names(names):
def key(name):
first, last = name.lower().split()
return (last, first)
return sorted(names, key=key)Exercise 2: A reduce that works with any iterable ✓ Passed
The my_reduce below works only with sequences, because it uses indexing and slicing. Rewrite it so that it works with any iterable (sets, generators, map objects...) and supports an optional initializer, like functools.reduce:
- my_reduce(fn, iterable) starts from the first element. - my_reduce(fn, iterable, initializer) starts from initializer, and returns it if the iterable is empty. - With an empty iterable and no initializer, raise TypeError.
Don't use functools.reduce. Tip: iter() and next() let you take the first element of any iterable.
_missing = object()
def my_reduce(fn, iterable, initializer=_missing):
result = iterable[0]
for x in iterable[1:]:
result = fn(result, x)
return result
import operator
def test_list():
"""reduces a list"""
assert my_reduce(operator.add, [1, 2, 3, 4]) == 10
def test_generator():
"""works with a generator (no indexing)"""
result = my_reduce(operator.mul, (n for n in range(1, 6)))
assert result == 120, f"got {result}"
def test_initializer():
"""uses the initializer as the starting value"""
assert my_reduce(lambda acc, s: acc + len(s), ['ab', 'cde'], 0) == 5
def test_empty_with_initializer():
"""returns the initializer for an empty iterable"""
assert my_reduce(operator.mul, [], 1) == 1
def test_empty_without_initializer():
"""raises TypeError for an empty iterable without initializer"""
try:
my_reduce(operator.add, [])
except TypeError:
return
assert False, "expected a TypeError"
def test_none_initializer():
"""None is a valid initializer"""
assert my_reduce(lambda acc, x: x, [], None) is None
Hints (3)
it = iter(iterable)gives you an iterator;next(it)returns its first element and raisesStopIterationif there is none.- A
forloop over the same iterator continues from wherenextleft off. - The
_missingsentinel lets you tell "no initializer" apart from an initializer ofNone: test it withis.
Show a solution
_missing = object()
def my_reduce(fn, iterable, initializer=_missing):
it = iter(iterable)
if initializer is _missing:
try:
result = next(it)
except StopIteration:
raise TypeError('my_reduce() of empty iterable with no initial value') from None
else:
result = initializer
for x in it:
result = fn(result, x)
return resultExercise 3: Which arguments are required? ✓ Passed
Using inspect.signature, write required_params(func) that returns a list of the names of the parameters a caller must supply, in order: parameters without a default value, excluding *args and **kwargs.
For def f(a, b=1, *args, c, d=2, **kwargs) the answer is ['a', 'c'].
import inspect
def required_params(func):
return list(inspect.signature(func).parameters)
def test_mixed():
"""positional, keyword-only, defaults and var-args"""
def f(a, b=1, *args, c, d=2, **kwargs):
pass
assert required_params(f) == ['a', 'c'], f"got {required_params(f)}"
def test_positional_only():
"""positional-only parameters count too"""
def g(x, /, y=0):
pass
assert required_params(g) == ['x'], f"got {required_params(g)}"
def test_none_required():
"""no required parameters"""
assert required_params(lambda *args, k=1, **kw: None) == []
def test_none_default():
"""a default of None is still a default"""
def h(a, b=None):
pass
assert required_params(h) == ['a'], f"got {required_params(h)}"
Hints (3)
inspect.signature(func).parametersmaps names toParameterobjects with.defaultand.kind.- A parameter has no default when
param.default is inspect.Parameter.empty. Don't test with== None:Noneis a perfectly good default. - Skip parameters whose kind is
VAR_POSITIONALorVAR_KEYWORD.
Show a solution
import inspect
def required_params(func):
var_kinds = (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD)
return [
name
for name, param in inspect.signature(func).parameters.items()
if param.default is param.empty and param.kind not in var_kinds
]Exercise 4: Compose functions ✓ Passed
Write compose(*funcs) that returns a new function of one argument applying the given functions from right to left: compose(f, g, h)(x) must equal f(g(h(x))).
With no functions, compose() returns a function that returns its argument unchanged. Try to use functools.reduce.
from functools import reduce
def compose(*funcs):
return funcs[0]
def test_two():
"""compose(f, g)(x) == f(g(x))"""
inc = lambda x: x + 1
dbl = lambda x: x * 2
assert compose(inc, dbl)(5) == 11, f"got {compose(inc, dbl)(5)}"
assert compose(dbl, inc)(5) == 12, f"got {compose(dbl, inc)(5)}"
def test_three():
"""works with built-ins and methods"""
f = compose(len, str.strip, str.lower)
assert f(' Hello ') == 5
def test_single():
"""a single function is returned unchanged in behavior"""
assert compose(abs)(-3) == 3
def test_identity():
"""compose() is the identity function"""
f = compose()
assert callable(f), "compose() must return a function"
obj = [1, 2]
assert f(obj) is obj
Hints (3)
- Start with composing just two functions:
lambda x: f(g(x)). reducecan fold that two-function step over all offuncs, left to right:compose2(compose2(f, g), h)isx -> f(g(h(x))).- Use the identity function
lambda x: xas the initializer, which also handles the empty case.
Show a solution
from functools import reduce
def compose(*funcs):
def compose2(f, g):
return lambda x: f(g(x))
return reduce(compose2, funcs, lambda x: x)