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 itemgetter
def 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 the output. We could also include a type hint in the variable assignment to look like this:

alternatives: List[Tuple[bool, Callable[[int], int]]] = [
etc,
]

The list is literally the same collection of four two-tuples. This definition clarifies that the list of tuples are a Boolean result and a callable function.

When we apply the filter() function using the itemgetter(0) parameter, we'll select those pairs with a True value in item zero of the tuple. Of those which are True, we'll use next() to extract the first item from the iterable created by the filter() function. The selected condition value is assigned to the _ variable; the selected function is assigned to the f variable. We can ignore the condition value (it will be True), and we can evaluate the f() function that was returned.

As with the previous example, we used lambdas to defer evaluation of the functions until after the conditions have been evaluated.

This semifact() function is also called double factorial. The definition of semifactorial is similar to the definition of factorial. The important difference is that it is the product of alternate numbers instead of all numbers. For examples, take a look at the following formulas:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset