Algorithms

Table of contents

  1. Module itertools — functions that create iterators
  2. Module functional — functional programming

Module itertools

Functions that create iterators.

chain(*iterables)
Lazy evaluation of iter(iterables.sum(list)).
> chain(1..2,1..4).list()
[1, 2, 1, 2, 3, 4]
prod(*iterables)
Return an iterator over the cartesian product of the iterables.
> prod(["x","y"],[0,1]).list()  
[["x", 0], ["x", 1], ["y", 0], ["y", 1]]
permutations(a)
Return an iterator over all permutations of a. The permuations are emitted in lexicographical order.
> permutations("abc").map(|t| t.join()).join("|") 
"abc|bac|bca|acb|cab|cba"
combinations(a,k)
Return an iterator over all k length combinations of a. The combinations are emitted in lexicographical order.
repeat(x), repeat(x,n)
Return an iterator that returns x over and over again. If n is given, the iterator will be exhausted after n calls.
i.step(m)
Returns an iterator that steps by skipping elements:
a.step(m).list() == [a[0],a[m],a[2*m],...]

Module functional

Functional programming.

fix(m,F)
Memoizing fixed point combinator.
fib = fix({},|f,n| 1 if n==1 or n==2 else f(n-1)+f(n-2))

fib = fix({1: 1, 2: 1}, |f,n| f(n-1)+f(n-2))
lazy(|| expression)
Create a new lazily evaluated expression. Evaluation of a such an expression x is done by x.value(). The expression is evaluated only once, the result then memoized for subsequent calls.
Lazy
Data type of lazily evaluated expressions.