summaryrefslogtreecommitdiffstats
path: root/Doc/library
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2010-04-10 07:01:32 (GMT)
committerRaymond Hettinger <python@rcn.com>2010-04-10 07:01:32 (GMT)
commita1d61d049591f10f8993e2ec591ba2b6acc10353 (patch)
tree51b74ba36482af7fc47d2e245d99c8a6fba559d2 /Doc/library
parent343314a11c6d91c2483c53d3871d3d69f8065fe7 (diff)
downloadcpython-a1d61d049591f10f8993e2ec591ba2b6acc10353.zip
cpython-a1d61d049591f10f8993e2ec591ba2b6acc10353.tar.gz
cpython-a1d61d049591f10f8993e2ec591ba2b6acc10353.tar.bz2
Fixup new itertools recipes.
Diffstat (limited to 'Doc/library')
-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 c914b53..0366fa2 100644
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -796,7 +796,7 @@ which incur interpreter overhead.
pools = map(tuple, args) * kwds.get('repeat', 1)
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
@@ -805,12 +805,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(xrange(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(imap(random.choice, [pool]*r), key=pool.index))
+ n = len(pool)
+ indices = sorted(random.randrange(n) for i in xrange(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