Functional Python Programming

(Wang) #1

Conditional Expressions and the Operator Module


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:


def semifact(n):


alternatives= [(n == 0, lambda n: 1),


(n == 1, lambda n: 1),


(n == 2, lambda n: 2),


(n > 2, lambda n: semifact(n-2)*n)]


c, f= next(filter(itemgetter(0), alternatives))


return f(n)


We defined the alternatives as a sequence of condition and function pairs. When
we apply the filter() function using the itemgetter(0) parameter, we'll select
those pairs with a True condition. Of those which are True, we'll select the first item
in the iterable created by the filter() function. The selected condition is assigned
to the c variable, the selected function is assigned to the f variable. We can ignore the
condition (it will be True), and we can evaluate the filter() function.


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 the
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 example, take a look
at the following formulas:


5!! 5=×3 1× , and 7!! 7=×5 3×× 1

Using the operator module instead


of lambdas


When using the max(), min(), and sorted() functions, we have an optional
key= parameter. The function provided as an argument value modifies the behavior
of the higher-order function. In many cases, we used simple lambda forms to pick
items from a tuple. Here are two examples we heavily relied on:


fst = lambda x: x[0]


snd = lambda x: x[1]

Free download pdf