Skip to content

Commit 7ded35d

Browse files
committed
Add random_derangement recipe
1 parent 33f8910 commit 7ded35d

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

Doc/library/random.rst

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -630,7 +630,8 @@ Recipes
630630
-------
631631

632632
These recipes show how to efficiently make random selections
633-
from the combinatoric iterators in the :mod:`itertools` module:
633+
from the combinatoric iterators in the :mod:`itertools` module
634+
or the :pypi:`more-itertools` project:
634635

635636
.. testcode::
636637
import random
@@ -661,6 +662,14 @@ from the combinatoric iterators in the :mod:`itertools` module:
661662
indices = sorted(random.choices(range(n), k=r))
662663
return tuple(pool[i] for i in indices)
663664

665+
def random_derangement(iterable):
666+
"Choose a permutation where no element is in its original position."
667+
seq = tuple(iterable)
668+
while True:
669+
perm = random_permutation(seq)
670+
if all(p != q for p, q in zip(seq, perm)):
671+
return perm
672+
664673
The default :func:`.random` returns multiples of 2⁻⁵³ in the range
665674
*0.0 ≤ x < 1.0*. All such numbers are evenly spaced and are exactly
666675
representable as Python floats. However, many other representable

0 commit comments

Comments
 (0)