File tree Expand file tree Collapse file tree 1 file changed +13
-1
lines changed Expand file tree Collapse file tree 1 file changed +13
-1
lines changed Original file line number Diff line number Diff line change @@ -630,7 +630,8 @@ Recipes
630
630
-------
631
631
632
632
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:
634
635
635
636
.. testcode ::
636
637
import random
@@ -661,6 +662,17 @@ from the combinatoric iterators in the :mod:`itertools` module:
661
662
indices = sorted(random.choices(range(n), k=r))
662
663
return tuple(pool[i] for i in indices)
663
664
665
+ def random_derangement(iterable):
666
+ "Choose a permutation where no element is in its original position."
667
+ seq = tuple(iterable)
668
+ if len(seq) < 2:
669
+ raise ValueError('derangments require at least two values')
670
+ perm = list(seq)
671
+ while True:
672
+ random.shuffle(perm)
673
+ if all(p != q for p, q in zip(seq, perm)):
674
+ return tuple(perm)
675
+
664
676
The default :func: `.random ` returns multiples of 2⁻⁵³ in the range
665
677
*0.0 ≤ x < 1.0 *. All such numbers are evenly spaced and are exactly
666
678
representable as Python floats. However, many other representable
You can’t perform that action at this time.
0 commit comments