diff options
author | Raymond Hettinger <python@rcn.com> | 2010-04-02 02:44:31 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2010-04-02 02:44:31 (GMT) |
commit | 4bfd3bda2ea7e71219fffe8b3e36c818b590be16 (patch) | |
tree | bc25308b4ee426e01e325745502046ec1e74d054 | |
parent | 8d1da0f5c3b8c6e3fa29e6ae7f891f699a041bb6 (diff) | |
download | cpython-4bfd3bda2ea7e71219fffe8b3e36c818b590be16.zip cpython-4bfd3bda2ea7e71219fffe8b3e36c818b590be16.tar.gz cpython-4bfd3bda2ea7e71219fffe8b3e36c818b590be16.tar.bz2 |
Add and update itertools recipes.
-rw-r--r-- | Doc/library/itertools.rst | 24 |
1 files changed, 23 insertions, 1 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index f83e976..663b93c 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -703,7 +703,8 @@ which incur interpreter overhead. return sum(imap(operator.mul, vec1, vec2)) def flatten(listOfLists): - return list(chain.from_iterable(listOfLists)) + "Flatten one level of nesting" + return chain.from_iterable(listOfLists) def repeatfunc(func, times=None, *args): """Repeat calls to func with specified arguments. @@ -790,6 +791,27 @@ which incur interpreter overhead. except exception: pass + def random_product(*args, **kwds): + "Random selection from itertools.product(*args, **kwds)" + pools = map(tuple, args) * kwds.get('repeat', 1) + return map(random.choice, pools) + + def random_permuation(iterable, r=None): + "Random selection from itertools.permutations(iterable, r)" + pool = list(iterable) + r = len(pool) if r is None else r + return random.sample(pool, r) + + def random_combination(iterable, r): + "Random selection from itertools.combinations(iterable, r)" + pool = list(iterable) + return sorted(random.sample(pool, r), key=pool.index) + + def random_combination_with_replacement(iterable, r): + "Random selection from itertools.combinations_with_replacement(iterable, r)" + pool = list(iterable) + return sorted(imap(random.choice, [pool]*r), key=pool.index) + Note, many of the above recipes can be optimized by replacing global lookups with local variables defined as default values. For example, the *dotproduct* recipe can be written as:: |