mirror of
https://github.com/python/cpython.git
synced 2025-11-03 19:34:08 +00:00
Take advantage of math.comb() in the nth_combination() recipe (#93027)
This commit is contained in:
parent
d59b2d0441
commit
59719a242d
1 changed files with 2 additions and 6 deletions
|
|
@ -992,12 +992,7 @@ which incur interpreter overhead.
|
||||||
"Equivalent to list(combinations(iterable, r))[index]"
|
"Equivalent to list(combinations(iterable, r))[index]"
|
||||||
pool = tuple(iterable)
|
pool = tuple(iterable)
|
||||||
n = len(pool)
|
n = len(pool)
|
||||||
if r < 0 or r > n:
|
c = math.comb(n, r)
|
||||||
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:
|
if index < 0:
|
||||||
index += c
|
index += c
|
||||||
if index < 0 or index >= c:
|
if index < 0 or index >= c:
|
||||||
|
|
@ -1071,6 +1066,7 @@ which incur interpreter overhead.
|
||||||
|
|
||||||
>>> import operator
|
>>> import operator
|
||||||
>>> import collections
|
>>> import collections
|
||||||
|
>>> import math
|
||||||
|
|
||||||
>>> take(10, count())
|
>>> take(10, count())
|
||||||
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue