summaryrefslogtreecommitdiffstats
path: root/Doc
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2010-04-10 07:08:41 (GMT)
committerRaymond Hettinger <python@rcn.com>2010-04-10 07:08:41 (GMT)
commit2fc70f05bc7b9b43538470e27c23378e025d73ec (patch)
treef5c826b5d76e3fea95c428c690679b2c137fb5f8 /Doc
parentd59ceb5b7c9cd6f0ea049ec953977a6f0aebc565 (diff)
downloadcpython-2fc70f05bc7b9b43538470e27c23378e025d73ec.zip
cpython-2fc70f05bc7b9b43538470e27c23378e025d73ec.tar.gz
cpython-2fc70f05bc7b9b43538470e27c23378e025d73ec.tar.bz2
Fixup new itertools recipes.
Diffstat (limited to 'Doc')
-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