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