One function

nth_combination_with_replacement in more-itertools/more-itertools

The author described this change as Simplify nth_combination_with_replacement. Fix incorrect exception.. It counts as a record because the check below fails on the code as it stood at def2d821c and passes on 06f318191, with nothing else changed between the two runs.

Fix saved2026-01-02
Sharing licenceMIT · LICENSE
Change size+4 7

What the code was meant to do, written into the code itself as a docstring

Equivalent to `list(combinations_with_replacement(iterable, r))[index]`. The subsequences with repetition of *iterable* that are of length *r* can be ordered lexicographically. :func:`nth_combination_with_replacement` computes the subsequence at sort position *index* directly, without computing the previous subsequences with replacement. `ValueError` will be raised If *r* is negative or greater than the length of *iterable*. `IndexError` will be raised if the given *index* is invalid.

The change

1111 >>> nth_combination_with_replacement(range(5), 3, 5)
1212 (0, 1, 1)
1313
14- ``ValueError`` will be raised If *r* is negative or greater than the length
15- of *iterable*.
14+ ``ValueError`` will be raised If *r* is negative.
1615 ``IndexError`` will be raised if the given *index* is invalid.
1716 """
1817 pool = tuple(iterable)
1918 n = len(pool)
20- if (r < 0) or (r > n):
19+ if r < 0:
2120 raise ValueError
22-
23- c = comb(n + r - 1, r)
21+ c = comb(n + r - 1, r) if n else 0 if r else 1
2422
2523 if index < 0:
2624 index += c
27-
28- if (index < 0) or (index >= c):
25+ if not 0 <= index < c:
2926 raise IndexError
3027
3128 result = []

The check that tells the two apart

failpass·tests/test_more.py::NthCombinationWithReplacementTests::test_basic

Check file tests/test_more.py, taken without changes from the fix and copied onto the older code, so the exact same check runs against both versions.

Origin and history

The code before itdef2d821c0a15ede86578660e7dc48e44bad9579
Broken version dated2026-01-02
Modulemore_itertools.more
Units changednth_combination_with_replacement
Fingerprint0e5bddcf06a80203
Checked2026-08-17 by goldset/0.1

Every field above is generated by our program. None of it is written by hand.

Other bugs found in more-itertools/more-itertools