summaryrefslogtreecommitdiffstats
path: root/Doc/library/itertools.rst
diff options
context:
space:
mode:
authorRaymond Hettinger <rhettinger@users.noreply.github.com>2018-01-13 18:35:40 (GMT)
committerGitHub <noreply@github.com>2018-01-13 18:35:40 (GMT)
commitd37258dd2e189141906bd234385096cd8e885d8d (patch)
tree7a48acb717506abcd109cbbbb5d649935790e404 /Doc/library/itertools.rst
parent0f31c74fcfdec8f9e6157de2c366f2273de81677 (diff)
downloadcpython-d37258dd2e189141906bd234385096cd8e885d8d.zip
cpython-d37258dd2e189141906bd234385096cd8e885d8d.tar.gz
cpython-d37258dd2e189141906bd234385096cd8e885d8d.tar.bz2
Add itertools recipe for directly finding the n-th combination (#5161)
Diffstat (limited to 'Doc/library/itertools.rst')
-rw-r--r--Doc/library/itertools.rst23
1 files changed, 23 insertions, 0 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
index 5af5422..0b3829f 100644
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -859,6 +859,29 @@ which incur interpreter overhead.
indices = sorted(random.randrange(n) for i in range(r))
return tuple(pool[i] for i in indices)
+ def nth_combination(iterable, r, index):
+ 'Equivalent to list(combinations(iterable, r))[index]'
+ pool = tuple(iterable)
+ n = len(pool)
+ if r < 0 or r > n:
+ raise ValueError
+ c = 1
+ k = min(r, n-r)
+ for i in range(1, k+1):
+ c = c * (n - k + i) // i
+ if index < 0:
+ index += c
+ if index < 0 or index >= c:
+ raise IndexError
+ result = []
+ while r:
+ c, n, r = c*r//n, n-1, r-1
+ while index >= c:
+ index -= c
+ c, n = c*(n-r)//n, n-1
+ result.append(pool[-1-n])
+ return tuple(result)
+
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::