Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Selected Python Libraries (Modules)
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 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.
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 )
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.
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 ) ) )
If you need to accumulate across all values in a container, one easy and quick way to do it is to use
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 ) )
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 ) )