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

99 >>> nth_permutation('ghijk', 2, 5)
1010 ('h', 'i')
1111
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.
1413 ``IndexError`` will be raised if the given *index* is invalid.
1514 """
1615 pool = list(iterable)
1716 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)
2620
2721 if index < 0:
2822 index += c
29-
3023 if not 0 <= index < c:
3124 raise IndexError
3225

The check that tells the two apart

failpass·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