summaryrefslogtreecommitdiffstats
path: root/Doc/library/itertools.rst
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2010-04-10 07:09:53 (GMT)
committerRaymond Hettinger <python@rcn.com>2010-04-10 07:09:53 (GMT)
commitc075f07a97e6413c4287ffde081900b675611372 (patch)
treef7dd204b2cfb2a9134c35ad2c950a6e48574c92e /Doc/library/itertools.rst
parent0ae7b5897eed3c26e392049fa7162c56a2a7f772 (diff)
downloadcpython-c075f07a97e6413c4287ffde081900b675611372.zip
cpython-c075f07a97e6413c4287ffde081900b675611372.tar.gz
cpython-c075f07a97e6413c4287ffde081900b675611372.tar.bz2
Fixup new itertools recipes.
Diffstat (limited to 'Doc/library/itertools.rst')
-rw-r--r--Doc/library/itertools.rst10
1 files changed, 7 insertions, 3 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
index 5c63b12..7326712 100644
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -709,7 +709,7 @@ which incur interpreter overhead.
pools = [tuple(pool) for pool in args] * repeat
return tuple(random.choice(pool) for pool in pools)
- def random_permuation(iterable, r=None):
+ def random_permutation(iterable, r=None):
"Random selection from itertools.permutations(iterable, r)"
pool = tuple(iterable)
r = len(pool) if r is None else r
@@ -718,12 +718,16 @@ which incur interpreter overhead.
def random_combination(iterable, r):
"Random selection from itertools.combinations(iterable, r)"
pool = tuple(iterable)
- return tuple(sorted(random.sample(pool, r), key=pool.index))
+ n = len(pool)
+ indices = sorted(random.sample(range(n), r))
+ return tuple(pool[i] for i in indices)
def random_combination_with_replacement(iterable, r):
"Random selection from itertools.combinations_with_replacement(iterable, r)"
pool = tuple(iterable)
- return tuple(sorted(map(random.choice, repeat(pool, r)), key=pool.index))
+ n = len(pool)
+ indices = sorted(random.randrange(n) for i in range(r))
+ return tuple(pool[i] for i in indices)
Note, many of the above recipes can be optimized by replacing global lookups
with local variables defined as default values. For example, the