Skip to content
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion Doc/library/random.rst
Original file line number Diff line number Diff line change
Expand Up @@ -630,7 +630,8 @@ Recipes
-------

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

.. testcode::
import random
Expand Down Expand Up @@ -661,6 +662,16 @@ from the combinatoric iterators in the :mod:`itertools` module:
indices = sorted(random.choices(range(n), k=r))
return tuple(pool[i] for i in indices)

def random_derangement(iterable):
"Choose a permutation where no element is in its original position."
seq = tuple(iterable)
if len(seq) < 2:
raise ValueError('derangments require at least two values')
while True:
perm = random_permutation(seq)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this depending on another recipe should be highlighted, as it may cause confusion.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, I will inline the code.

if all(p != q for p, q in zip(seq, perm)):
return perm

The default :func:`.random` returns multiples of 2⁻⁵³ in the range
*0.0 ≤ x < 1.0*. All such numbers are evenly spaced and are exactly
representable as Python floats. However, many other representable
Expand Down
Loading