First-Class Functions · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What does this print?
def double(a: int) -> int:
    return a * 2

print(double('ab'))
2. Which of these is not a valid lambda expression?
3. What does this print?
words = ['bb', 'a', 'cc', 'd']
print(sorted(words, key=len))
4. What does this print?
d = {'x': 3, 'y': 1, 'z': 2}
print(sorted(d, key=d.get))
5. What does this print?
def f(a, b=1, *args, c, d=2, **kwargs):
    pass

print(f.__defaults__, f.__kwdefaults__)
6. What does this print?
class Greeter:
    def greet(self):
        return 'hi'

g = Greeter()
print(callable(Greeter), callable(g), callable(g.greet))
7. What does this print?
m = map(str.upper, ['a', 'b'])
print(list(m), list(m))
8. What does this print?
print(list(zip('abc', range(5))))
9. What does this print?
from functools import reduce
print(reduce(lambda acc, x: acc + x, [1, 2, 3], 10))
10. What does this print?
print(all([]), any([]))
11. What does this print?
from functools import partial
import operator

x = 5
add_x = partial(operator.add, x)
x = 100
print(add_x(1))
12. What does this print?
from operator import itemgetter
pairs = [(1, 'b'), (2, 'a'), (1, 'a')]
print(sorted(pairs, key=itemgetter(0)))

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

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'].

Hints (3)
  1. sorted(names, key=...) returns a new list. The key function receives one full name.
  2. Return a tuple (surname, first_name) from the key, so ties on the surname are broken by the first name.
  3. 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

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.

Hints (3)
  1. it = iter(iterable) gives you an iterator; next(it) returns its first element and raises StopIteration if there is none.
  2. A for loop over the same iterator continues from where next left off.
  3. The _missing sentinel lets you tell "no initializer" apart from an initializer of None: test it with is.
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 result

Exercise 3: Which arguments are required?

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'].

Hints (3)
  1. inspect.signature(func).parameters maps names to Parameter objects with .default and .kind.
  2. A parameter has no default when param.default is inspect.Parameter.empty. Don't test with == None: None is a perfectly good default.
  3. Skip parameters whose kind is VAR_POSITIONAL or VAR_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

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.

Hints (3)
  1. Start with composing just two functions: lambda x: f(g(x)).
  2. reduce can fold that two-function step over all of funcs, left to right: compose2(compose2(f, g), h) is x -> f(g(h(x))).
  3. Use the identity function lambda x: x as 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)