Filtering true conditional expressions

We have a number of ways of determining which expression is True. In the previous example, we loaded the keys into a dictionary. Because of the way the dictionary is loaded, only one value will be preserved with a key of True.

Here's another variation to this theme, written using the filter() function:

from operator import itemgetterdef semifact(n: int) -> int:    alternatives = [        (n == 0, lambda n: 1),        (n == 1, lambda n: 1),        (n == 2, lambda n: 2),        (n > 2, lambda n: semifact(n-2)*n)    ]    _, f = next(filter(itemgetter(0), alternatives))    return f(n)

We defined the alternatives as a sequence of condition and function pairs. Each item in the as a condition based on the input and a lambda item that will produce ...

Get Functional Python Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.