Skip to content
Open
Changes from all 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
28 changes: 27 additions & 1 deletion src/sage/sets/set.py
Original file line number Diff line number Diff line change
Expand Up @@ -899,9 +899,19 @@ def cardinality(self):

sage: Set([1,1]).cardinality()
1
sage: Set(GF(998244353)).cardinality()
998244353
"""
from sage.rings.integer import Integer
return Integer(len(self.set()))
o = self.object()
if o is self:
Comment on lines +906 to +907
Copy link
Contributor

Choose a reason for hiding this comment

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

how can o is self happen?

Copy link
Contributor Author

@user202729 user202729 Nov 17, 2025

Choose a reason for hiding this comment

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

Set_object_binary does Set_object.__init__(self, self, category=category)

many of them override this method, but better safe than sorry.

(seriously it's probably better to not make Set_object_binary inherit from Set_object at all... but I consider that out of scope)

return Integer(len(self.set()))
if isinstance(o, (list, tuple, set, frozenset)):
return Integer(len(o))
try:
return o.cardinality()
except (AttributeError, NotImplementedError):
return Integer(len(self.set()))

def __len__(self):
"""
Expand Down Expand Up @@ -957,7 +967,23 @@ def _repr_(self):

sage: Set()
{}
sage: repr(Set(GF(998244353))).replace("...", "LITERAL ELLIPSIS")
'Set of elements of Finite Field of size 998244353 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, LITERAL ELLIPSIS}'
"""
try:
if self.cardinality() > 20:
from itertools import islice
o = self.object()
l = list(islice(o, 0, 20))
s = "{" + ", ".join(map(repr, l)) + ", ...}"
assert len(l) == 20, (f"incorrect cardinality {self.cardinality()} "
f"reported for object type {type(self)} containing {l}")
if o is not self: # safeguard infinite loop if subclass is weird
s = f"Set of elements of {o!r} = {s}"
return s
except NotImplementedError:
pass
py_set = self.set()
if not py_set:
return "{}"
Expand Down
Loading