summaryrefslogtreecommitdiffstats
path: root/Lib
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 /Lib
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 'Lib')
-rw-r--r--Lib/test/test_itertools.py33
1 files changed, 33 insertions, 0 deletions
diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py
index a359905..4fcc02a 100644
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -2262,6 +2262,30 @@ Samuele
... # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
... return next(filter(pred, iterable), default)
+>>> 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)
+
+
This is not part of the examples but it tests to make sure the definitions
perform as purported.
@@ -2345,6 +2369,15 @@ True
>>> first_true('ABC0DEF1', '9', str.isdigit)
'0'
+>>> population = 'ABCDEFGH'
+>>> for r in range(len(population) + 1):
+... seq = list(combinations(population, r))
+... for i in range(len(seq)):
+... assert nth_combination(population, r, i) == seq[i]
+... for i in range(-len(seq), 0):
+... assert nth_combination(population, r, i) == seq[i]
+
+
"""
__test__ = {'libreftest' : libreftest}