Skip to content

Commit 15134a0

Browse files
author
Release Manager
committed
sagemathgh-39766: Fix Derangements(0) to return 1 and yield the empty permutation Fixes sagemath#39734 ### What this does This PR fixes the behavior of `Derangements(0)` in two ways: - `Derangements(0).cardinality()` now correctly returns `1` instead of `0`, aligning with standard combinatorics conventions and OEIS [A000166](https://oeis.org/A000166). - `Derangements(0).list()` now returns `[[]]`, representing the single (empty) derangement of the empty set, instead of an empty list. These changes ensure consistency with mathematical definitions and fix an inconsistency between `Derangements(0)` and `Permutations(0)`. ### Why this matters Returning `1` for `Derangements(0).cardinality()` is consistent with the recursive definition of derangements and is mathematically correct. Without this fix, Sage currently contradicts standard references and user expectations. ### 📝 Checklist - [x] The title is concise and informative. - [x] The description explains in detail what this PR is about. - [x] I have linked a relevant issue or discussion. - [x] I have created tests covering the changes. - [x] I have updated the documentation and checked the documentation preview. ### ⌛ Dependencies None. URL: sagemath#39766 Reported by: TinaJin0228 Reviewer(s): Darij Grinberg
2 parents c7f56b9 + 9f22ac9 commit 15134a0

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

src/sage/combinat/derangements.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,9 @@ def __iter__(self):
281281
sage: D = Derangements([1,1,2,2,2])
282282
sage: D.list()
283283
[]
284+
sage: D = Derangements(0)
285+
sage: D.list()
286+
[[]]
284287
"""
285288
if self.__multi:
286289
for p in Permutations(self._set):
@@ -309,7 +312,10 @@ def _iter_der(self, n):
309312
[3, 4, 1, 2],
310313
[2, 1, 4, 3]]
311314
"""
312-
if n <= 1:
315+
if n == 0:
316+
yield []
317+
return
318+
elif n == 1:
313319
return
314320
elif n == 2:
315321
yield [2, 1]
@@ -359,7 +365,9 @@ def _count_der(self, n):
359365
sage: D._count_der(5)
360366
44
361367
"""
362-
if n <= 1:
368+
if n == 0:
369+
return Integer(1)
370+
if n == 1:
363371
return Integer(0)
364372
if n == 2:
365373
return Integer(1)
@@ -415,6 +423,9 @@ def cardinality(self):
415423
sage: D = Derangements([1,1,2,2,2])
416424
sage: D.cardinality()
417425
0
426+
sage: D = Derangements(0)
427+
sage: D.cardinality()
428+
1
418429
"""
419430
if self.__multi:
420431
sL = set(self._set)

0 commit comments

Comments
 (0)