Book Image

Functional Python Programming

By : Steven F. Lott, Steven F. Lott
Book Image

Functional Python Programming

By: Steven F. Lott, Steven F. Lott

Overview of this book

Table of Contents (23 chapters)
Functional Python Programming
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Reducing with operators


We'll look at one more way that we might try to use the operator definitions. We can use them with the built-in functools.reduce() function. The sum() function, for example, can be defined as follows:

sum= functools.partial(functools.reduce, operator.add)

We created a partially evaluated version of the reduce() function with the first argument supplied. In this case, it's the + operator, implemented via the operator.add() function.

If we have a requirement for a similar function that computes a product, we can define it like this:

prod= functools.partial(functools.reduce, operator.mul)

This follows the pattern shown in the preceding example. We have a partially evaluated reduce() function with the first argument of * operator, as implemented by the operator.mul() function.

It's not clear whether we can do similar things with too many of the other operators. We might be able to find a use for the operator.concat() function as well as the operator.and() and operator...