Skip to content

Commit 9a3d7e3

Browse files
committed
Clarify how derangements treats duplicate inputs
1 parent 0b34b64 commit 9a3d7e3

1 file changed

Lines changed: 14 additions & 2 deletions

File tree

more_itertools/more.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -886,8 +886,20 @@ def derangements(iterable, r=None):
886886
[(2, 0), (2, 3), (3, 0)]
887887
888888
Elements are treated as unique based on their position, not on their value.
889-
If the input elements are unique, there will be no repeated values within a
890-
permutation.
889+
890+
Consider the Secret Santa example with two *different* people who have
891+
the *same* name. Then there are two valid gift assignments even though
892+
it might appear that a person is assigned to themselves:
893+
894+
>>> names = ['Alice', 'Bob', 'Bob']
895+
>>> list(derangements(names))
896+
[('Bob', 'Bob', 'Alice'), ('Bob', 'Alice', 'Bob')]
897+
898+
To avoid confusion, make the inputs distinct:
899+
900+
>>> deduped = [f'{name}{index}' for index, name in enumerate(names)]
901+
>>> list(derangements(deduped))
902+
[('Bob1', 'Bob2', 'Alice0'), ('Bob2', 'Alice0', 'Bob1')]
891903
892904
The number of derangements of a set of size *n* is known as the
893905
"subfactorial of n". For n > 0, the subfactorial is:

0 commit comments

Comments
 (0)