Functional Python Programming

(Wang) #1

More Itertools Techniques


0.98: Per capita consumption of cheese (US)Pounds (USDA) vs Per
capita consumption of mozzarella cheese (US)Pounds (USDA)


0.88: US crude oil imports from VenezuelaMillions of barrels
(Dept. of Energy) vs Per capita consumption of high fructose corn
syrup (US)Pounds (USDA)


It's not at all clear what this pattern means. We used a simple expression,
combinations(range(9), 2), to enumerate all the possible combinations of data.
This kind of succinct, expressive technique makes it easier to focus on the data
analysis issues instead of the Combinatoric algorithm considerations.


Recipes


The itertools chapter of the Python library documentation is outstanding. The basic
definitions are followed by a series of recipes that are extremely clear and helpful.
Since there's no reason to reproduce these, we'll reference them here. They are the
required reading materials on functional programming in Python.


Section 10.1.2, Itertools Recipes, of Python Standard Library is a wonderful resource.
Visit https://docs.python.org/3/library/itertools.html#itertools-
recipes more details.


These function definitions aren't importable functions in the itertools modules.
These are ideas that need to be read and understood and then, perhaps, copied or
modified before inclusion in an application.


The following table summarizes some recipes that show functional programming
algorithms built from the itertools basics:


Function
Name

Arguments Results

powerset (iterable) This generates all the subsets of the iterable. Each
subset is actually a tuple object, not a set instance.
random_
product

(*args,
repeat=1)

This randomly selects from itertools.
product(*args, **kwds).
random_
permutation

(iterable,
r=None)

This randomly selects from itertools.
permutations(iterable, r).
random_
combination

(iterable,
r)

This randomly selects from itertools.
combinations(iterable, r).
Free download pdf