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
| 11 | 11 | >>> nth_combination_with_replacement(range(5), 3, 5) | |
| 12 | 12 | (0, 1, 1) | |
| 13 | 13 | ||
| 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. | |
| 16 | 15 | ``IndexError`` will be raised if the given *index* is invalid. | |
| 17 | 16 | """ | |
| 18 | 17 | pool = tuple(iterable) | |
| 19 | 18 | n = len(pool) | |
| 20 | - | if (r < 0) or (r > n): | |
| 19 | + | if r < 0: | |
| 21 | 20 | 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 | |
| 24 | 22 | ||
| 25 | 23 | if index < 0: | |
| 26 | 24 | index += c | |
| 27 | - | ||
| 28 | - | if (index < 0) or (index >= c): | |
| 25 | + | if not 0 <= index < c: | |
| 29 | 26 | raise IndexError | |
| 30 | 27 | ||
| 31 | 28 | result = [] |
The check that tells the two apart
fail→pass·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
- 2026-07-19chunked
- 2026-07-03sliced
- 2026-06-30tail
- 2026-06-30interleave_evenly
- 2026-04-01windowed
- 2026-01-02nth_permutation