@@ -1136,24 +1136,6 @@ The following recipes have a more mathematical flavor:
1136
1136
n = n // p * (p - 1)
1137
1137
return n
1138
1138
1139
- def nth_combination(iterable, r, index):
1140
- "Equivalent to list(combinations(iterable, r))[index]"
1141
- pool = tuple(iterable)
1142
- n = len(pool)
1143
- c = math.comb(n, r)
1144
- if index < 0:
1145
- index += c
1146
- if index < 0 or index >= c:
1147
- raise IndexError
1148
- result = []
1149
- while r:
1150
- c, n, r = c*r//n, n-1, r-1
1151
- while index >= c:
1152
- index -= c
1153
- c, n = c*(n-r)//n, n-1
1154
- result.append(pool[-1-n])
1155
- return tuple(result)
1156
-
1157
1139
1158
1140
.. doctest ::
1159
1141
:hide:
@@ -1577,20 +1559,6 @@ The following recipes have a more mathematical flavor:
1577
1559
>>> first_true(' ABC0DEF1' , ' 9' , str .isdigit)
1578
1560
'0'
1579
1561
1580
- >>> population = ' ABCDEFGH'
1581
- >>> for r in range (len (population) + 1 ):
1582
- ... seq = list (combinations(population, r))
1583
- ... for i in range (len (seq)):
1584
- ... assert nth_combination(population, r, i) == seq[i]
1585
- ... for i in range (- len (seq), 0 ):
1586
- ... assert nth_combination(population, r, i) == seq[i]
1587
-
1588
- >>> iterable = ' abcde'
1589
- >>> r = 3
1590
- >>> combos = list (combinations(iterable, r))
1591
- >>> all (nth_combination(iterable, r, i) == comb for i, comb in enumerate (combos))
1592
- True
1593
-
1594
1562
1595
1563
.. testcode ::
1596
1564
:hide:
@@ -1617,6 +1585,24 @@ The following recipes have a more mathematical flavor:
1617
1585
for (a, _), (b, c) in pairwise(pairwise(iterable)):
1618
1586
yield a, b, c
1619
1587
1588
+ def nth_combination(iterable, r, index):
1589
+ "Equivalent to list(combinations(iterable, r))[index]"
1590
+ pool = tuple(iterable)
1591
+ n = len(pool)
1592
+ c = math.comb(n, r)
1593
+ if index < 0:
1594
+ index += c
1595
+ if index < 0 or index >= c:
1596
+ raise IndexError
1597
+ result = []
1598
+ while r:
1599
+ c, n, r = c*r//n, n-1, r-1
1600
+ while index >= c:
1601
+ index -= c
1602
+ c, n = c*(n-r)//n, n-1
1603
+ result.append(pool[-1-n])
1604
+ return tuple(result)
1605
+
1620
1606
1621
1607
.. doctest ::
1622
1608
:hide:
@@ -1632,3 +1618,17 @@ The following recipes have a more mathematical flavor:
1632
1618
1633
1619
>>> list (triplewise(' ABCDEFG' ))
1634
1620
[('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E'), ('D', 'E', 'F'), ('E', 'F', 'G')]
1621
+
1622
+ >>> population = ' ABCDEFGH'
1623
+ >>> for r in range (len (population) + 1 ):
1624
+ ... seq = list (combinations(population, r))
1625
+ ... for i in range (len (seq)):
1626
+ ... assert nth_combination(population, r, i) == seq[i]
1627
+ ... for i in range (- len (seq), 0 ):
1628
+ ... assert nth_combination(population, r, i) == seq[i]
1629
+
1630
+ >>> iterable = ' abcde'
1631
+ >>> r = 3
1632
+ >>> combos = list (combinations(iterable, r))
1633
+ >>> all (nth_combination(iterable, r, i) == comb for i, comb in enumerate (combos))
1634
+ True
0 commit comments