Skip to content

Libraries

Neal Davis edited this page Oct 1, 2016 · 2 revisions

Selected Python Libraries (Modules)

itertools

Iterators are data types which contain other values and are compatible with looping. For instance, you can iterate over a string or a list. We generally do this in sequence or simply over every member of the container, but there are quite a few efficient and sophisticated alternatives. itertools supports many of these; we will focus on only a few of them: combinations, permutations, and accumulate.

itertools.combinations

Use combinations when we want to carry out analysis on each subset of a group. For instance, to obtain each pair in a set:

from itertools import combinations
for pair in combinations( 'ABCD',2 ):
    print( pair )

Note that the order is preserved. The number specifies the number of elements possible combinations should contain.

Examples

The following code generates all possible teams of three partners in a group.

partners = [ 'Sergey', 'Julian', 'Azra',
             'Berenice', 'Ogden', 'Gloria' ]
for group in combinations( partners,3 ):
    print( group )

itertools.permutations

In contrast to itertools.combinations (which preserves order), we use permutations when we want all of the elements in every possible order:

from itertools import permutations
for triplet in permutations( 'ABCD',3 ):
    print( triplet )

Both of these functions tend to be more useful in computer science and informatics than in engineering, but they occasionally come in useful for scientists.

Examples

Consider a network of cities connected by roads.

The following code lets you traverse every city in all possible orders from all possible starting locations:

from itertools import permutations
cities = [ 'St Albans', 'Montford', 'Kramer',
           'Cariston', 'Howardsville', 'Winslow' ]
print( list( permutations( cities,6 ) ) )

itertools.accumulate

If you need to accumulate across all values in a container, one easy and quick way to do it is to use accumulate:

from itertools import accumulate
values = [ 0.3, 0.5, 1.2, -0.6, 0.3, 0.2 ]
cumulative_sums = accumulate( values )
print( list( cumulative_sums ) )

Examples

This code approximately calculates the cumulative probability of the normal distribution:

# calculate values of normal distribution
from math import exp, sqrt, pi
x = [ -3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0,
      0.5, 1.0, 1.5, 2.0, 2.5, 3.0 ]
normal_dist = [ ]
for i in x:
    normal_dist.append( (exp(-0.5*i*i)) / (sqrt(2)*pi) )
# calculate approximate cumulative probability of normal distribution
from itertools import accumulate
cumul_sum = accumulate( normal_dist )
print( list( cumul_sum ) )

Resources

math

string

You can’t perform that action at this time.