COMBINATORICS
from itertools import *
# Permutations (order matters)
permutations([1,2,3]) # all 3! arrangements
permutations([1,2,3], 2) # choose 2
# → (1,2),(1,3),(2,1),(2,3),(3,1),(3,2)
# Combinations (order doesn't matter)
combinations([1,2,3], 2) # choose 2
# → (1,2),(1,3),(2,3)
# Combinations with repetition
combinations_with_replacement([1,2], 2)
# → (1,1),(1,2),(2,2)
# Cartesian product
product([1,2], ['a','b']) # all pairs
# → (1,'a'),(1,'b'),(2,'a'),(2,'b')
product(range(2), repeat=3) # 3-bit binary numbers
ITERATORS & SEQUENCES
# Chaining & Grouping
chain([1,2], [3,4]) # 1,2,3,4
groupby([1,1,2,2,3]) # group consecutive
# Accumulate (prefix sum!)
accumulate([1,2,3,4]) # 1,3,6,10
# Infinite Sequences
count(10) # 10,11,12...
cycle([1,2,3]) # 1,2,3,1,2,3...
repeat(42, 5) # 42 x5
# Slicing an iterator:
islice(count(1), 5) # [1,2,3,4,5]