Python filter True conditional expression
Python Filtering True Conditional Expressions There are several ways to determine which expressions evaluate to True. The previous example loaded the key into a dictionary. This dictionary loading method only retains the value for which the key is True.
Another variation of this model, written using the filter()
function, is as follows:
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)
This defines all alternatives as a sequence of condition and function pairs, where each term is a condition based on an input and an anonymous function that produces an output. Variable assignments can also include a type hint, as shown below:
alternatives: List[Tuple[bool, Callable[[int], int]]] = [
etc,
]
This list actually represents the same set of four tuples. The definition clarifies that the list of tuples contains a boolean value and a callable function.
When the filter()
function is applied using the itemgetter(0)
parameter, we select pairs where the zeroth item in the tuple evaluates to True. For these pairs where the value is True, we use the next()
method to extract the first item from the iterable object created by the filter()
function. The selected condition value is assigned to the _
variable, and the selected function is assigned to the f
variable. The conditional value (which evaluates to True) can be ignored, and only the returned function f()
is evaluated.
In the previous example, an anonymous function was used to delay function evaluation until after the conditional was evaluated.
The semifact()
function is also known as the double factorial. The definition of the semifactorial is similar to the factorial, the main difference being that the semifactorial is the product of alternating numbers rather than all the numbers. For example, the following two formulas:
- 5!!=5×3×1
- 7!!=7×5×3×1