One function
nth_permutation in more-itertools/more-itertools
The author described this change as “Simplify nth_permutation. Fix incorrect exception.”. It counts as a record because the check below fails on the code as it stood at 6b32fbfba and passes on def2d821c, with nothing else changed between the two runs.
Fix saved2026-01-02
Sharing licenceMIT · LICENSE
Change size+4 −11
What the code was meant to do, written into the code itself as a docstring
Equivalent to `list(permutations(iterable, r))[index]`` The subsequences of *iterable* that are of length *r* where order is important can be ordered lexicographically. :func:`nth_permutation` computes the subsequence at sort position *index* directly, without computing the previous subsequences. `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
| 9 | 9 | >>> nth_permutation('ghijk', 2, 5) | |
| 10 | 10 | ('h', 'i') | |
| 11 | 11 | ||
| 12 | - | ``ValueError`` will be raised If *r* is negative or greater than the length | |
| 13 | - | of *iterable*. | |
| 12 | + | ``ValueError`` will be raised If *r* is negative. | |
| 14 | 13 | ``IndexError`` will be raised if the given *index* is invalid. | |
| 15 | 14 | """ | |
| 16 | 15 | pool = list(iterable) | |
| 17 | 16 | n = len(pool) | |
| 18 | - | ||
| 19 | - | if r is None or r == n: | |
| 20 | - | r, c = n, factorial(n) | |
| 21 | - | elif not 0 <= r < n: | |
| 22 | - | raise ValueError | |
| 23 | - | else: | |
| 24 | - | c = perm(n, r) | |
| 25 | - | assert c > 0 # factorial(n)>0, and r<n so perm(n,r) is never zero | |
| 17 | + | if r is None: | |
| 18 | + | r = n | |
| 19 | + | c = perm(n, r) | |
| 26 | 20 | ||
| 27 | 21 | if index < 0: | |
| 28 | 22 | index += c | |
| 29 | - | ||
| 30 | 23 | if not 0 <= index < c: | |
| 31 | 24 | raise IndexError | |
| 32 | 25 |
The check that tells the two apart
fail→pass·tests/test_recipes.py::NthPermutationTests::test_invalid_index
Check file tests/test_recipes.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 it6b32fbfba127d6b4aaf57d6b254b2ab5fc80ae76
Broken version dated2026-01-01
Modulemore_itertools.more
Units changednth_permutation
Fingerprint5669b01cd6d103f3
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_combination_with_replacement