[Python-checkins] Take advantage of math.comb() in the nth_combination() recipe (GH-93027) (#93032)

rhettinger webhook-mailer at python.org
Fri May 20 19:34:45 EDT 2022


https://github.com/python/cpython/commit/b52e44d9330b6a02c4215b664cd92e7562242635
commit: b52e44d9330b6a02c4215b664cd92e7562242635
branch: 3.11
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: rhettinger <rhettinger at users.noreply.github.com>
date: 2022-05-20T18:34:30-05:00
summary:

Take advantage of math.comb() in the nth_combination() recipe (GH-93027) (#93032)

files:
M Doc/library/itertools.rst

diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
index 26c9253cb7f5f..416c4eca5eb48 100644
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -992,12 +992,7 @@ which incur interpreter overhead.
        "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
+       c = math.comb(n, r)
        if index < 0:
            index += c
        if index < 0 or index >= c:
@@ -1071,6 +1066,7 @@ which incur interpreter overhead.
 
     >>> import operator
     >>> import collections
+    >>> import math
 
     >>> take(10, count())
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]



More information about the Python-checkins mailing list