Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagesmc
Path: blob/master/src/sage/sets/set.py
8817 views
1
"""
2
Sets
3
4
AUTHORS:
5
6
- William Stein (2005) - first version
7
8
- William Stein (2006-02-16) - large number of documentation and
9
examples; improved code
10
11
- Mike Hansen (2007-3-25) - added differences and symmetric
12
differences; fixed operators
13
14
- Florent Hivert (2010-06-17) - Adapted to categories
15
16
- Nicolas M. Thiery (2011-03-15) - Added subset and superset methods
17
"""
18
19
#*****************************************************************************
20
# Copyright (C) 2005 William Stein <[email protected]>
21
#
22
# Distributed under the terms of the GNU General Public License (GPL)
23
#
24
# This code is distributed in the hope that it will be useful,
25
# but WITHOUT ANY WARRANTY; without even the implied warranty of
26
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
27
# General Public License for more details.
28
#
29
# The full text of the GPL is available at:
30
#
31
# http://www.gnu.org/licenses/
32
#*****************************************************************************
33
34
from sage.structure.element import Element
35
from sage.structure.parent import Parent, Set_generic
36
from sage.misc.latex import latex
37
import sage.rings.infinity
38
from sage.misc.misc import is_iterator
39
from sage.categories.sets_cat import Sets
40
from sage.categories.enumerated_sets import EnumeratedSets
41
42
def Set(X):
43
r"""
44
Create the underlying set of ``X``.
45
46
If ``X`` is a list, tuple, Python set, or ``X.is_finite()`` is
47
``True``, this returns a wrapper around Python's enumerated immutable
48
``frozenset`` type with extra functionality. Otherwise it returns a
49
more formal wrapper.
50
51
If you need the functionality of mutable sets, use Python's
52
builtin set type.
53
54
EXAMPLES::
55
56
sage: X = Set(GF(9,'a'))
57
sage: X
58
{0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2}
59
sage: type(X)
60
<class 'sage.sets.set.Set_object_enumerated_with_category'>
61
sage: Y = X.union(Set(QQ))
62
sage: Y
63
Set-theoretic union of {0, 1, 2, a, a + 1, a + 2, 2*a, 2*a + 1, 2*a + 2} and Set of elements of Rational Field
64
sage: type(Y)
65
<class 'sage.sets.set.Set_object_union_with_category'>
66
67
Usually sets can be used as dictionary keys.
68
69
::
70
71
sage: d={Set([2*I,1+I]):10}
72
sage: d # key is randomly ordered
73
{{I + 1, 2*I}: 10}
74
sage: d[Set([1+I,2*I])]
75
10
76
sage: d[Set((1+I,2*I))]
77
10
78
79
The original object is often forgotten.
80
81
::
82
83
sage: v = [1,2,3]
84
sage: X = Set(v)
85
sage: X
86
{1, 2, 3}
87
sage: v.append(5)
88
sage: X
89
{1, 2, 3}
90
sage: 5 in X
91
False
92
93
Set also accepts iterators, but be careful to only give *finite* sets.
94
95
::
96
97
sage: list(Set(iter([1, 2, 3, 4, 5])))
98
[1, 2, 3, 4, 5]
99
100
We can also create sets from different types::
101
102
sage: Set([Sequence([3,1], immutable=True), 5, QQ, Partition([3,1,1])])
103
{Rational Field, [3, 1, 1], [3, 1], 5}
104
105
However each of the objects must be hashable::
106
107
sage: Set([QQ, [3, 1], 5])
108
Traceback (most recent call last):
109
...
110
TypeError: unhashable type: 'list'
111
112
TESTS::
113
114
sage: Set(Primes())
115
Set of all prime numbers: 2, 3, 5, 7, ...
116
sage: Set(Subsets([1,2,3])).cardinality()
117
8
118
sage: Set(iter([1,2,3]))
119
{1, 2, 3}
120
sage: type(_)
121
<class 'sage.sets.set.Set_object_enumerated_with_category'>
122
sage: S = Set([])
123
sage: TestSuite(S).run()
124
"""
125
if is_Set(X):
126
return X
127
128
if isinstance(X, Element):
129
raise TypeError, "Element has no defined underlying set"
130
elif isinstance(X, (list, tuple, set, frozenset)):
131
return Set_object_enumerated(frozenset(X))
132
try:
133
if X.is_finite():
134
return Set_object_enumerated(X)
135
except AttributeError:
136
pass
137
if is_iterator(X):
138
# Note we are risking an infinite loop here,
139
# but this is the way Python behaves too: try
140
# sage: set(an iterator which does not terminate)
141
return Set_object_enumerated(list(X))
142
return Set_object(X)
143
144
def EnumeratedSet(X):
145
"""
146
Return the enumerated set associated to ``X``.
147
148
The input object ``X`` must be finite.
149
150
EXAMPLES::
151
152
sage: EnumeratedSet([1,1,2,3])
153
doctest:1: DeprecationWarning: EnumeratedSet is deprecated; use Set instead.
154
See http://trac.sagemath.org/8930 for details.
155
{1, 2, 3}
156
sage: EnumeratedSet(ZZ)
157
Traceback (most recent call last):
158
...
159
ValueError: X (=Integer Ring) must be finite
160
"""
161
from sage.misc.superseded import deprecation
162
deprecation(8930, 'EnumeratedSet is deprecated; use Set instead.')
163
try:
164
if not X.is_finite():
165
raise ValueError, "X (=%s) must be finite"%X
166
except AttributeError:
167
pass
168
return Set_object_enumerated(X)
169
170
def is_Set(x):
171
"""
172
Returns ``True`` if ``x`` is a Sage :class:`Set_object` (not to be confused
173
with a Python set).
174
175
EXAMPLES::
176
177
sage: from sage.sets.set import is_Set
178
sage: is_Set([1,2,3])
179
False
180
sage: is_Set(set([1,2,3]))
181
False
182
sage: is_Set(Set([1,2,3]))
183
True
184
sage: is_Set(Set(QQ))
185
True
186
sage: is_Set(Primes())
187
True
188
"""
189
return isinstance(x, Set_generic)
190
191
class Set_object(Set_generic):
192
r"""
193
A set attached to an almost arbitrary object.
194
195
EXAMPLES::
196
197
sage: K = GF(19)
198
sage: Set(K)
199
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}
200
sage: S = Set(K)
201
202
sage: latex(S)
203
\left\{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18\right\}
204
sage: TestSuite(S).run()
205
206
sage: latex(Set(ZZ))
207
\Bold{Z}
208
209
TESTS:
210
211
See trac ticket :trac:`14486`::
212
213
sage: 0 == Set([1]), Set([1]) == 0
214
(False, False)
215
sage: 1 == Set([0]), Set([0]) == 1
216
(False, False)
217
"""
218
def __init__(self, X):
219
"""
220
Create a Set_object
221
222
This function is called by the Set function; users
223
shouldn't call this directly.
224
225
EXAMPLES::
226
227
sage: type(Set(QQ))
228
<class 'sage.sets.set.Set_object_with_category'>
229
230
TESTS::
231
232
sage: _a, _b = get_coercion_model().canonical_coercion(Set([0]), 0)
233
Traceback (most recent call last):
234
...
235
TypeError: no common canonical parent for objects with parents:
236
'<class 'sage.sets.set.Set_object_enumerated_with_category'>'
237
and 'Integer Ring'
238
"""
239
from sage.rings.integer import is_Integer
240
if isinstance(X, (int,long)) or is_Integer(X):
241
# The coercion model will try to call Set_object(0)
242
raise ValueError('underlying object cannot be an integer')
243
Parent.__init__(self, category=Sets())
244
self.__object = X
245
246
def __hash__(self):
247
"""
248
Return the hash value of ``self``.
249
250
EXAMPLES::
251
252
sage: hash(Set(QQ)) == hash(QQ)
253
True
254
"""
255
return hash(self.__object)
256
257
def _latex_(self):
258
r"""
259
Return latex representation of this set.
260
261
This is often the same as the latex representation of this
262
object when the object is infinite.
263
264
EXAMPLES::
265
266
sage: latex(Set(QQ))
267
\Bold{Q}
268
269
When the object is finite or a special set then the latex
270
representation can be more interesting.
271
272
::
273
274
sage: print latex(Primes())
275
\text{\texttt{Set{ }of{ }all{ }prime{ }numbers:{ }2,{ }3,{ }5,{ }7,{ }...}}
276
sage: print latex(Set([1,1,1,5,6]))
277
\left\{1, 5, 6\right\}
278
"""
279
return latex(self.__object)
280
281
def _repr_(self):
282
"""
283
Print representation of this set.
284
285
EXAMPLES::
286
287
sage: X = Set(ZZ)
288
sage: X
289
Set of elements of Integer Ring
290
sage: X.rename('{ integers }')
291
sage: X
292
{ integers }
293
"""
294
return "Set of elements of %s"%self.__object
295
296
def __iter__(self):
297
"""
298
Iterate over the elements of this set.
299
300
EXAMPLES::
301
302
sage: X = Set(ZZ)
303
sage: I = X.__iter__()
304
sage: I.next()
305
0
306
sage: I.next()
307
1
308
sage: I.next()
309
-1
310
sage: I.next()
311
2
312
"""
313
return self.__object.__iter__()
314
315
an_element = EnumeratedSets.ParentMethods.__dict__['_an_element_from_iterator']
316
317
def __contains__(self, x):
318
"""
319
Return ``True`` if `x` is in ``self``.
320
321
EXAMPLES::
322
323
sage: X = Set(ZZ)
324
sage: 5 in X
325
True
326
sage: GF(7)(3) in X
327
True
328
sage: 2/1 in X
329
True
330
sage: 2/1 in ZZ
331
True
332
sage: 2/3 in X
333
False
334
335
Finite fields better illustrate the difference between
336
``__contains__`` for objects and their underlying sets.
337
338
sage: X = Set(GF(7))
339
sage: X
340
{0, 1, 2, 3, 4, 5, 6}
341
sage: 5/3 in X
342
False
343
sage: 5/3 in GF(7)
344
False
345
sage: Set(GF(7)).union(Set(GF(5)))
346
{0, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 0}
347
sage: Set(GF(7)).intersection(Set(GF(5)))
348
{}
349
"""
350
return x in self.__object
351
352
def __cmp__(self, right):
353
r"""
354
Compare ``self`` and ``right``.
355
356
If right is not a :class:`Set_object` compare types. If ``right`` is
357
also a :class:`Set_object`, returns comparison on the underlying
358
objects.
359
360
.. NOTE::
361
362
If `X < Y` is true this does *not* necessarily mean
363
that `X` is a subset of `Y`. Also, any two sets can be
364
compared still, but the result need not be meaningful
365
if they are not equal.
366
367
EXAMPLES::
368
369
sage: Set(ZZ) == Set(QQ)
370
False
371
sage: Set(ZZ) < Set(QQ)
372
True
373
sage: Primes() == Set(QQ)
374
False
375
376
The following is random, illustrating that comparison of
377
sets is not the subset relation, when they are not equal::
378
379
sage: Primes() < Set(QQ) # random
380
True or False
381
"""
382
if not isinstance(right, Set_object):
383
return cmp(type(self), type(right))
384
return cmp(self.__object, right.__object)
385
386
def union(self, X):
387
"""
388
Return the union of ``self`` and ``X``.
389
390
EXAMPLES::
391
392
sage: Set(QQ).union(Set(ZZ))
393
Set-theoretic union of Set of elements of Rational Field and Set of elements of Integer Ring
394
sage: Set(QQ) + Set(ZZ)
395
Set-theoretic union of Set of elements of Rational Field and Set of elements of Integer Ring
396
sage: X = Set(QQ).union(Set(GF(3))); X
397
Set-theoretic union of Set of elements of Rational Field and {0, 1, 2}
398
sage: 2/3 in X
399
True
400
sage: GF(3)(2) in X
401
True
402
sage: GF(5)(2) in X
403
False
404
sage: Set(GF(7)) + Set(GF(3))
405
{0, 1, 2, 3, 4, 5, 6, 1, 2, 0}
406
"""
407
if is_Set(X):
408
if self is X:
409
return self
410
return Set_object_union(self, X)
411
raise TypeError, "X (=%s) must be a Set"%X
412
413
def __add__(self, X):
414
"""
415
Return the union of ``self`` and ``X``.
416
417
EXAMPLES::
418
419
sage: Set(RealField()) + Set(QQ^5)
420
Set-theoretic union of Set of elements of Real Field with 53 bits of precision and Set of elements of Vector space of dimension 5 over Rational Field
421
sage: Set(GF(3)) + Set(GF(2))
422
{0, 1, 2, 0, 1}
423
sage: Set(GF(2)) + Set(GF(4,'a'))
424
{0, 1, a, a + 1}
425
sage: Set(GF(8,'b')) + Set(GF(4,'a'))
426
{0, 1, b, b + 1, b^2, b^2 + 1, b^2 + b, b^2 + b + 1, a, a + 1, 1, 0}
427
"""
428
return self.union(X)
429
430
def __or__(self, X):
431
"""
432
Return the union of ``self`` and ``X``.
433
434
EXAMPLES::
435
436
sage: Set([2,3]) | Set([3,4])
437
{2, 3, 4}
438
sage: Set(ZZ) | Set(QQ)
439
Set-theoretic union of Set of elements of Integer Ring and Set of elements of Rational Field
440
"""
441
442
return self.union(X)
443
444
def intersection(self, X):
445
r"""
446
Return the intersection of ``self`` and ``X``.
447
448
EXAMPLES::
449
450
sage: X = Set(ZZ).intersection(Primes())
451
sage: 4 in X
452
False
453
sage: 3 in X
454
True
455
456
sage: 2/1 in X
457
True
458
459
sage: X = Set(GF(9,'b')).intersection(Set(GF(27,'c')))
460
sage: X
461
{}
462
463
sage: X = Set(GF(9,'b')).intersection(Set(GF(27,'b')))
464
sage: X
465
{}
466
"""
467
if is_Set(X):
468
if self is X:
469
return self
470
return Set_object_intersection(self, X)
471
raise TypeError, "X (=%s) must be a Set"%X
472
473
474
def difference(self, X):
475
r"""
476
Return the set difference ``self - X``.
477
478
EXAMPLES::
479
480
sage: X = Set(ZZ).difference(Primes())
481
sage: 4 in X
482
True
483
sage: 3 in X
484
False
485
486
sage: 4/1 in X
487
True
488
489
sage: X = Set(GF(9,'b')).difference(Set(GF(27,'c')))
490
sage: X
491
{0, 1, 2, b, b + 1, b + 2, 2*b, 2*b + 1, 2*b + 2}
492
493
sage: X = Set(GF(9,'b')).difference(Set(GF(27,'b')))
494
sage: X
495
{0, 1, 2, b, b + 1, b + 2, 2*b, 2*b + 1, 2*b + 2}
496
"""
497
if is_Set(X):
498
if self is X:
499
return Set([])
500
return Set_object_difference(self, X)
501
raise TypeError, "X (=%s) must be a Set"%X
502
503
def symmetric_difference(self, X):
504
r"""
505
Returns the symmetric difference of ``self`` and ``X``.
506
507
EXAMPLES::
508
509
sage: X = Set([1,2,3]).symmetric_difference(Set([3,4]))
510
sage: X
511
{1, 2, 4}
512
"""
513
514
if is_Set(X):
515
if self is X:
516
return Set([])
517
return Set_object_symmetric_difference(self, X)
518
raise TypeError, "X (=%s) must be a Set"%X
519
520
521
def __sub__(self, X):
522
"""
523
Return the difference of ``self`` and ``X``.
524
525
EXAMPLES::
526
527
sage: X = Set(ZZ).difference(Primes())
528
sage: Y = Set(ZZ) - Primes()
529
sage: X == Y
530
True
531
"""
532
return self.difference(X)
533
534
def __and__(self, X):
535
"""
536
Returns the intersection of ``self`` and ``X``.
537
538
EXAMPLES::
539
540
sage: Set([2,3]) & Set([3,4])
541
{3}
542
sage: Set(ZZ) & Set(QQ)
543
Set-theoretic intersection of Set of elements of Integer Ring and Set of elements of Rational Field
544
"""
545
546
return self.intersection(X)
547
548
def __xor__(self, X):
549
"""
550
Returns the symmetric difference of ``self`` and ``X``.
551
552
EXAMPLES::
553
554
sage: X = Set([1,2,3,4])
555
sage: Y = Set([1,2])
556
sage: X.symmetric_difference(Y)
557
{3, 4}
558
sage: X.__xor__(Y)
559
{3, 4}
560
"""
561
return self.symmetric_difference(X)
562
563
def cardinality(self):
564
"""
565
Return the cardinality of this set, which is either an integer or
566
``Infinity``.
567
568
EXAMPLES::
569
570
sage: Set(ZZ).cardinality()
571
+Infinity
572
sage: Primes().cardinality()
573
+Infinity
574
sage: Set(GF(5)).cardinality()
575
5
576
sage: Set(GF(5^2,'a')).cardinality()
577
25
578
"""
579
try:
580
if not self.is_finite():
581
return sage.rings.infinity.infinity
582
except AttributeError:
583
pass
584
try:
585
return self.__object.cardinality()
586
except AttributeError:
587
pass
588
try:
589
return len(self.__object)
590
except TypeError:
591
raise NotImplementedError, "computation of cardinality of %s not yet implemented"%self.__object
592
593
def is_empty(self):
594
"""
595
Return boolean representing emptiness of the set.
596
597
OUTPUT:
598
599
True if the set is empty, false if otherwise.
600
601
EXAMPLES::
602
603
sage: Set([]).is_empty()
604
True
605
sage: Set([0]).is_empty()
606
False
607
sage: Set([1..100]).is_empty()
608
False
609
sage: Set(SymmetricGroup(2).list()).is_empty()
610
False
611
sage: Set(ZZ).is_empty()
612
False
613
614
TESTS::
615
616
sage: Set([]).is_empty()
617
True
618
sage: Set([1,2,3]).is_empty()
619
False
620
sage: Set([1..100]).is_empty()
621
False
622
sage: Set(DihedralGroup(4).list()).is_empty()
623
False
624
sage: Set(QQ).is_empty()
625
False
626
"""
627
return not self.__nonzero__()
628
629
def is_finite(self):
630
"""
631
Return ``True`` if ``self`` is finite.
632
633
EXAMPLES::
634
635
sage: Set(QQ).is_finite()
636
False
637
sage: Set(GF(250037)).is_finite()
638
True
639
sage: Set(Integers(2^1000000)).is_finite()
640
True
641
sage: Set([1,'a',ZZ]).is_finite()
642
True
643
"""
644
if isinstance(self.__object, (set, frozenset, tuple, list)):
645
return True
646
else:
647
return self.__object.is_finite()
648
649
def object(self):
650
"""
651
Return underlying object.
652
653
EXAMPLES::
654
655
sage: X = Set(QQ)
656
sage: X.object()
657
Rational Field
658
sage: X = Primes()
659
sage: X.object()
660
Set of all prime numbers: 2, 3, 5, 7, ...
661
"""
662
return self.__object
663
664
665
def subsets(self,size=None):
666
"""
667
Return the :class:`Subsets` object representing the subsets of a set.
668
If size is specified, return the subsets of that size.
669
670
EXAMPLES::
671
672
sage: X = Set([1,2,3])
673
sage: list(X.subsets())
674
[{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}]
675
sage: list(X.subsets(2))
676
[{1, 2}, {1, 3}, {2, 3}]
677
678
"""
679
from sage.combinat.subset import Subsets
680
return Subsets(self,size)
681
682
class Set_object_enumerated(Set_object):
683
"""
684
A finite enumerated set.
685
"""
686
def __init__(self, X):
687
"""
688
Initialize ``self``.
689
690
EXAMPLES::
691
692
sage: S = Set(GF(19)); S
693
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}
694
sage: print latex(S)
695
\left\{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18\right\}
696
sage: TestSuite(S).run()
697
"""
698
Set_object.__init__(self, X)
699
700
def cardinality(self):
701
"""
702
Return the cardinality of ``self``.
703
704
EXAMPLES::
705
706
sage: Set([1,1]).cardinality()
707
1
708
"""
709
return len(self.set())
710
711
def __len__(self):
712
"""
713
EXAMPLES::
714
715
sage: len(Set([1,1]))
716
1
717
"""
718
return self.cardinality()
719
720
721
def __iter__(self):
722
r"""
723
Iterating through the elements of ``self``.
724
725
EXAMPLES::
726
727
sage: S = Set(GF(19))
728
sage: I = iter(S)
729
sage: I.next()
730
0
731
sage: I.next()
732
1
733
sage: I.next()
734
2
735
sage: I.next()
736
3
737
"""
738
for x in self.set():
739
yield x
740
741
def _latex_(self):
742
r"""
743
Return the LaTeX representation of ``self``.
744
745
EXAMPLES::
746
747
sage: S = Set(GF(2))
748
sage: latex(S)
749
\left\{0, 1\right\}
750
"""
751
return '\\left\\{' + ', '.join([latex(x) for x in self.set()]) + '\\right\\}'
752
753
def _repr_(self):
754
r"""
755
Return the string representation of ``self``.
756
757
EXAMPLES::
758
759
sage: S = Set(GF(2))
760
sage: S
761
{0, 1}
762
"""
763
s = repr(self.set())
764
return "{" + s[5:-2] + "}"
765
766
def list(self):
767
"""
768
Return the elements of ``self``, as a list.
769
770
EXAMPLES::
771
772
sage: X = Set(GF(8,'c'))
773
sage: X
774
{0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1}
775
sage: X.list()
776
[0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1]
777
sage: type(X.list())
778
<type 'list'>
779
780
.. TODO::
781
782
FIXME: What should be the order of the result?
783
That of ``self.object()``? Or the order given by
784
``set(self.object())``? Note that :meth:`__getitem__` is
785
currently implemented in term of this list method, which
786
is really inefficient ...
787
"""
788
return list(set(self.object()))
789
790
def set(self):
791
"""
792
Return the Python set object associated to this set.
793
794
Python has a notion of finite set, and often Sage sets
795
have an associated Python set. This function returns
796
that set.
797
798
EXAMPLES::
799
800
sage: X = Set(GF(8,'c'))
801
sage: X
802
{0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1}
803
sage: X.set()
804
set([0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1])
805
sage: type(X.set())
806
<type 'set'>
807
sage: type(X)
808
<class 'sage.sets.set.Set_object_enumerated_with_category'>
809
"""
810
return set(self.object())
811
812
def frozenset(self):
813
"""
814
Return the Python frozenset object associated to this set,
815
which is an immutable set (hence hashable).
816
817
EXAMPLES::
818
819
sage: X = Set(GF(8,'c'))
820
sage: X
821
{0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1}
822
sage: s = X.set(); s
823
set([0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1])
824
sage: hash(s)
825
Traceback (most recent call last):
826
...
827
TypeError: unhashable type: 'set'
828
sage: s = X.frozenset(); s
829
frozenset([0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1])
830
sage: hash(s)
831
-1390224788 # 32-bit
832
561411537695332972 # 64-bit
833
sage: type(s)
834
<type 'frozenset'>
835
"""
836
return frozenset(self.object())
837
838
def __hash__(self):
839
"""
840
Return the hash of ``self`` (as a ``frozenset``).
841
842
EXAMPLES::
843
844
sage: s = Set(GF(8,'c'))
845
sage: hash(s) == hash(s)
846
True
847
"""
848
return hash(self.frozenset())
849
850
def __cmp__(self, other):
851
"""
852
Compare the sets ``self`` and ``other``.
853
854
EXAMPLES::
855
856
sage: X = Set(GF(8,'c'))
857
sage: X == Set(GF(8,'c'))
858
True
859
sage: X == Set(GF(4,'a'))
860
False
861
sage: Set(QQ) == Set(ZZ)
862
False
863
"""
864
if isinstance(other, Set_object_enumerated):
865
if self.set() == other.set():
866
return 0
867
return -1
868
else:
869
return Set_object.__cmp__(self, other)
870
871
def issubset(self, other):
872
r"""
873
Return whether ``self`` is a subset of ``other``.
874
875
INPUT:
876
877
- ``other`` -- a finite Set
878
879
EXAMPLES::
880
881
sage: X = Set([1,3,5])
882
sage: Y = Set([0,1,2,3,5,7])
883
sage: X.issubset(Y)
884
True
885
sage: Y.issubset(X)
886
False
887
sage: X.issubset(X)
888
True
889
890
TESTS::
891
892
sage: len([Z for Z in Y.subsets() if Z.issubset(X)])
893
8
894
"""
895
if not isinstance(other, Set_object_enumerated):
896
raise NotImplementedError
897
return self.set().issubset(other.set())
898
899
def issuperset(self, other):
900
r"""
901
Return whether ``self`` is a superset of ``other``.
902
903
INPUT:
904
905
- ``other`` -- a finite Set
906
907
EXAMPLES::
908
909
sage: X = Set([1,3,5])
910
sage: Y = Set([0,1,2,3,5])
911
sage: X.issuperset(Y)
912
False
913
sage: Y.issuperset(X)
914
True
915
sage: X.issuperset(X)
916
True
917
918
TESTS::
919
920
sage: len([Z for Z in Y.subsets() if Z.issuperset(X)])
921
4
922
"""
923
if not isinstance(other, Set_object_enumerated):
924
raise NotImplementedError
925
return self.set().issuperset(other.set())
926
927
def union(self, other):
928
"""
929
Return the union of ``self`` and ``other``.
930
931
EXAMPLES::
932
933
sage: X = Set(GF(8,'c'))
934
sage: Y = Set([GF(8,'c').0, 1, 2, 3])
935
sage: X
936
{0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1}
937
sage: Y
938
{1, c, 3, 2}
939
sage: X.union(Y)
940
{0, 1, c, c + 1, c^2, c^2 + 1, c^2 + c, c^2 + c + 1, 2, 3}
941
"""
942
if not isinstance(other, Set_object_enumerated):
943
return Set_object.union(self, other)
944
return Set_object_enumerated(self.set().union(other.set()))
945
946
def intersection(self, other):
947
"""
948
Return the intersection of ``self`` and ``other``.
949
950
EXAMPLES::
951
952
sage: X = Set(GF(8,'c'))
953
sage: Y = Set([GF(8,'c').0, 1, 2, 3])
954
sage: X.intersection(Y)
955
{1, c}
956
"""
957
if not isinstance(other, Set_object_enumerated):
958
return Set_object.intersection(self, other)
959
return Set_object_enumerated(self.set().intersection(other.set()))
960
961
def difference(self, other):
962
"""
963
Return the set difference ``self - other``.
964
965
EXAMPLES::
966
967
sage: X = Set([1,2,3,4])
968
sage: Y = Set([1,2])
969
sage: X.difference(Y)
970
{3, 4}
971
sage: Z = Set(ZZ)
972
sage: W = Set([2.5, 4, 5, 6])
973
sage: W.difference(Z)
974
{2.50000000000000}
975
"""
976
if not isinstance(other, Set_object_enumerated):
977
return Set([x for x in self if x not in other])
978
return Set_object_enumerated(self.set().difference(other.set()))
979
980
def symmetric_difference(self, other):
981
"""
982
Return the symmetric difference of ``self`` and ``other``.
983
984
EXAMPLES::
985
986
sage: X = Set([1,2,3,4])
987
sage: Y = Set([1,2])
988
sage: X.symmetric_difference(Y)
989
{3, 4}
990
sage: Z = Set(ZZ)
991
sage: W = Set([2.5, 4, 5, 6])
992
sage: U = W.symmetric_difference(Z)
993
sage: 2.5 in U
994
True
995
sage: 4 in U
996
False
997
sage: V = Z.symmetric_difference(W)
998
sage: V == U
999
True
1000
sage: 2.5 in V
1001
True
1002
sage: 6 in V
1003
False
1004
"""
1005
if not isinstance(other, Set_object_enumerated):
1006
return Set_object.symmetric_difference(self, other)
1007
return Set_object_enumerated(self.set().symmetric_difference(other.set()))
1008
1009
class Set_object_union(Set_object):
1010
"""
1011
A formal union of two sets.
1012
"""
1013
def __init__(self, X, Y):
1014
r"""
1015
Initialize ``self``.
1016
1017
EXAMPLES::
1018
1019
sage: S = Set(QQ^2)
1020
sage: T = Set(ZZ)
1021
sage: X = S.union(T); X
1022
Set-theoretic union of Set of elements of Vector space of dimension 2 over Rational Field and Set of elements of Integer Ring
1023
1024
sage: latex(X)
1025
\Bold{Q}^{2} \cup \Bold{Z}
1026
1027
sage: TestSuite(X).run()
1028
"""
1029
self.__X = X
1030
self.__Y = Y
1031
Set_object.__init__(self, self)
1032
1033
def __cmp__(self, right):
1034
r"""
1035
Try to compare ``self`` and ``right``.
1036
1037
.. NOTE::
1038
1039
Comparison is basically not implemented, or rather it could
1040
say sets are not equal even though they are. I don't know
1041
how one could implement this for a generic union of sets in
1042
a meaningful manner. So be careful when using this.
1043
1044
EXAMPLES::
1045
1046
sage: Y = Set(ZZ^2).union(Set(ZZ^3))
1047
sage: X = Set(ZZ^3).union(Set(ZZ^2))
1048
sage: X == Y
1049
True
1050
sage: Y == X
1051
True
1052
1053
This illustrates that equality testing for formal unions
1054
can be misleading in general.
1055
1056
::
1057
1058
sage: Set(ZZ).union(Set(QQ)) == Set(QQ)
1059
False
1060
"""
1061
if not is_Set(right):
1062
return -1
1063
if not isinstance(right, Set_object_union):
1064
return -1
1065
if self.__X == right.__X and self.__Y == right.__Y or \
1066
self.__X == right.__Y and self.__Y == right.__X:
1067
return 0
1068
return -1
1069
1070
def _repr_(self):
1071
r"""
1072
Return string representation of ``self``.
1073
1074
EXAMPLES::
1075
1076
sage: Set(ZZ).union(Set(GF(5)))
1077
Set-theoretic union of Set of elements of Integer Ring and {0, 1, 2, 3, 4}
1078
"""
1079
return "Set-theoretic union of %s and %s"%(self.__X,
1080
self.__Y)
1081
1082
def _latex_(self):
1083
r"""
1084
Return latex representation of ``self``.
1085
1086
EXAMPLES::
1087
1088
sage: latex(Set(ZZ).union(Set(GF(5))))
1089
\Bold{Z} \cup \left\{0, 1, 2, 3, 4\right\}
1090
"""
1091
return '%s \\cup %s'%(latex(self.__X), latex(self.__Y))
1092
1093
def __iter__(self):
1094
"""
1095
Return iterator over the elements of ``self``.
1096
1097
EXAMPLES::
1098
1099
sage: [x for x in Set(GF(3)).union(Set(GF(2)))]
1100
[0, 1, 2, 0, 1]
1101
"""
1102
for x in self.__X:
1103
yield x
1104
for y in self.__Y:
1105
yield y
1106
1107
def __contains__(self, x):
1108
"""
1109
Return ``True`` if ``x`` is an element of ``self``.
1110
1111
EXAMPLES::
1112
1113
sage: X = Set(GF(3)).union(Set(GF(2)))
1114
sage: GF(5)(1) in X
1115
False
1116
sage: GF(3)(2) in X
1117
True
1118
sage: GF(2)(0) in X
1119
True
1120
sage: GF(5)(0) in X
1121
False
1122
"""
1123
return x in self.__X or x in self.__Y
1124
1125
def cardinality(self):
1126
"""
1127
Return the cardinality of this set.
1128
1129
EXAMPLES::
1130
1131
sage: X = Set(GF(3)).union(Set(GF(2)))
1132
sage: X
1133
{0, 1, 2, 0, 1}
1134
sage: X.cardinality()
1135
5
1136
1137
sage: X = Set(GF(3)).union(Set(ZZ))
1138
sage: X.cardinality()
1139
+Infinity
1140
"""
1141
return self.__X.cardinality() + self.__Y.cardinality()
1142
1143
class Set_object_intersection(Set_object):
1144
"""
1145
Formal intersection of two sets.
1146
"""
1147
def __init__(self, X, Y):
1148
r"""
1149
Initialize ``self``.
1150
1151
EXAMPLES::
1152
1153
sage: S = Set(QQ^2)
1154
sage: T = Set(ZZ)
1155
sage: X = S.intersection(T); X
1156
Set-theoretic intersection of Set of elements of Vector space of dimension 2 over Rational Field and Set of elements of Integer Ring
1157
sage: latex(X)
1158
\Bold{Q}^{2} \cap \Bold{Z}
1159
1160
sage: X = Set(IntegerRange(100)).intersection(Primes())
1161
sage: TestSuite(X).run()
1162
"""
1163
self.__X = X
1164
self.__Y = Y
1165
Set_object.__init__(self, self)
1166
1167
1168
def __cmp__(self, right):
1169
r"""
1170
Try to compare ``self`` and ``right``.
1171
1172
.. NOTE::
1173
1174
Comparison is basically not implemented, or rather it could
1175
say sets are not equal even though they are. I don't know
1176
how one could implement this for a generic intersection of
1177
sets in a meaningful manner. So be careful when using this.
1178
1179
EXAMPLES::
1180
1181
sage: Y = Set(ZZ).intersection(Set(QQ))
1182
sage: X = Set(QQ).intersection(Set(ZZ))
1183
sage: X == Y
1184
True
1185
sage: Y == X
1186
True
1187
1188
This illustrates that equality testing for formal unions
1189
can be misleading in general.
1190
1191
::
1192
1193
sage: Set(ZZ).intersection(Set(QQ)) == Set(QQ)
1194
False
1195
"""
1196
if not is_Set(right):
1197
return -1
1198
if not isinstance(right, Set_object_intersection):
1199
return -1
1200
if self.__X == right.__X and self.__Y == right.__Y or \
1201
self.__X == right.__Y and self.__Y == right.__X:
1202
return 0
1203
return -1
1204
1205
def _repr_(self):
1206
"""
1207
Return string representation of ``self``.
1208
1209
EXAMPLES::
1210
1211
sage: X = Set(ZZ).intersection(Set(QQ)); X
1212
Set-theoretic intersection of Set of elements of Integer Ring and Set of elements of Rational Field
1213
sage: X.rename('Z /\ Q')
1214
sage: X
1215
Z /\ Q
1216
"""
1217
return "Set-theoretic intersection of %s and %s"%(self.__X,
1218
self.__Y)
1219
1220
def _latex_(self):
1221
r"""
1222
Return latex representation of ``self``.
1223
1224
EXAMPLES::
1225
1226
sage: X = Set(ZZ).intersection(Set(QQ))
1227
sage: latex(X)
1228
\Bold{Z} \cap \Bold{Q}
1229
"""
1230
return '%s \\cap %s'%(latex(self.__X), latex(self.__Y))
1231
1232
def __iter__(self):
1233
"""
1234
Return iterator through elements of ``self``.
1235
1236
``self`` is a formal intersection of `X` and `Y` and this function is
1237
implemented by iterating through the elements of `X` and for
1238
each checking if it is in `Y`, and if yielding it.
1239
1240
EXAMPLES::
1241
1242
sage: X = Set(ZZ).intersection(Primes())
1243
sage: I = X.__iter__()
1244
sage: I.next()
1245
2
1246
"""
1247
for x in self.__X:
1248
if x in self.__Y:
1249
yield x
1250
1251
def __contains__(self, x):
1252
"""
1253
Return ``True`` if ``self`` contains ``x``.
1254
1255
Since ``self`` is a formal intersection of `X` and `Y` this function
1256
returns ``True`` if both `X` and `Y` contains ``x``.
1257
1258
EXAMPLES::
1259
1260
sage: X = Set(QQ).intersection(Set(RR))
1261
sage: 5 in X
1262
True
1263
sage: ComplexField().0 in X
1264
False
1265
1266
Any specific floating-point number in Sage is to finite precision,
1267
hence it is rational::
1268
1269
sage: RR(sqrt(2)) in X
1270
True
1271
1272
Real constants are not rational::
1273
1274
sage: pi in X
1275
False
1276
"""
1277
return x in self.__X and x in self.__Y
1278
1279
def cardinality(self):
1280
"""
1281
This tries to return the cardinality of this formal intersection.
1282
1283
.. WARNING::
1284
1285
This is not likely to work in very much generality,
1286
and may just hang if either set involved is infinite.
1287
1288
EXAMPLES::
1289
1290
sage: X = Set(GF(13)).intersection(Set(ZZ))
1291
sage: X.cardinality()
1292
13
1293
"""
1294
return len(list(self))
1295
1296
1297
1298
class Set_object_difference(Set_object):
1299
"""
1300
Formal difference of two sets.
1301
"""
1302
def __init__(self, X, Y):
1303
r"""
1304
Initialize ``self``.
1305
1306
EXAMPLES::
1307
1308
sage: S = Set(QQ)
1309
sage: T = Set(ZZ)
1310
sage: X = S.difference(T); X
1311
Set-theoretic difference between Set of elements of Rational Field and Set of elements of Integer Ring
1312
sage: latex(X)
1313
\Bold{Q} - \Bold{Z}
1314
1315
sage: TestSuite(X).run()
1316
"""
1317
self.__X = X
1318
self.__Y = Y
1319
Set_object.__init__(self, self)
1320
1321
1322
def __cmp__(self, right):
1323
r"""
1324
Try to compare ``self`` and ``right``.
1325
1326
.. NOTE::
1327
1328
Comparison is basically not implemented, or rather it could
1329
say sets are not equal even though they are. I don't know
1330
how one could implement this for a generic intersection of
1331
sets in a meaningful manner. So be careful when using
1332
this.
1333
1334
EXAMPLES::
1335
1336
sage: Y = Set(ZZ).difference(Set(QQ))
1337
sage: Y == Set([])
1338
False
1339
sage: X = Set(QQ).difference(Set(ZZ))
1340
sage: Y == X
1341
False
1342
sage: Z = X.difference(Set(ZZ))
1343
sage: Z == X
1344
False
1345
1346
This illustrates that equality testing for formal unions
1347
can be misleading in general.
1348
1349
::
1350
1351
sage: X == Set(QQ).difference(Set(ZZ))
1352
True
1353
"""
1354
if not is_Set(right):
1355
return -1
1356
if not isinstance(right, Set_object_difference):
1357
return -1
1358
if self.__X == right.__X and self.__Y == right.__Y:
1359
return 0
1360
return -1
1361
1362
def _repr_(self):
1363
"""
1364
Return string representation of ``self``.
1365
1366
EXAMPLES::
1367
1368
sage: X = Set(QQ).difference(Set(ZZ)); X
1369
Set-theoretic difference between Set of elements of Rational Field and Set of elements of Integer Ring
1370
sage: X.rename('Q - Z')
1371
sage: X
1372
Q - Z
1373
"""
1374
return "Set-theoretic difference between %s and %s"%(self.__X,
1375
self.__Y)
1376
1377
def _latex_(self):
1378
r"""
1379
Return latex representation of ``self``.
1380
1381
EXAMPLES::
1382
1383
sage: X = Set(QQ).difference(Set(ZZ))
1384
sage: latex(X)
1385
\Bold{Q} - \Bold{Z}
1386
"""
1387
return '%s - %s'%(latex(self.__X), latex(self.__Y))
1388
1389
def __iter__(self):
1390
"""
1391
Return iterator through elements of ``self``.
1392
1393
``self`` is a formal difference of `X` and `Y` and this function
1394
is implemented by iterating through the elements of `X` and for
1395
each checking if it is not in `Y`, and if yielding it.
1396
1397
EXAMPLES::
1398
1399
sage: X = Set(ZZ).difference(Primes())
1400
sage: I = X.__iter__()
1401
sage: I.next()
1402
0
1403
sage: I.next()
1404
1
1405
sage: I.next()
1406
-1
1407
sage: I.next()
1408
-2
1409
sage: I.next()
1410
-3
1411
"""
1412
for x in self.__X:
1413
if x not in self.__Y:
1414
yield x
1415
1416
def __contains__(self, x):
1417
"""
1418
Return ``True`` if ``self`` contains ``x``.
1419
1420
Since ``self`` is a formal intersection of `X` and `Y` this function
1421
returns ``True`` if both `X` and `Y` contains ``x``.
1422
1423
EXAMPLES::
1424
1425
sage: X = Set(QQ).difference(Set(ZZ))
1426
sage: 5 in X
1427
False
1428
sage: ComplexField().0 in X
1429
False
1430
sage: sqrt(2) in X # since sqrt(2) is not a numerical approx
1431
False
1432
sage: sqrt(RR(2)) in X # since sqrt(RR(2)) is a numerical approx
1433
True
1434
sage: 5/2 in X
1435
True
1436
"""
1437
return x in self.__X and x not in self.__Y
1438
1439
def cardinality(self):
1440
"""
1441
This tries to return the cardinality of this formal intersection.
1442
1443
.. WARNING::
1444
1445
This is not likely to work in very much generality,
1446
and may just hang if either set involved is infinite.
1447
1448
EXAMPLES::
1449
1450
sage: X = Set(GF(13)).difference(Set(Primes()))
1451
sage: X.cardinality()
1452
8
1453
"""
1454
return len(list(self))
1455
1456
class Set_object_symmetric_difference(Set_object):
1457
"""
1458
Formal symmetric difference of two sets.
1459
"""
1460
def __init__(self, X, Y):
1461
r"""
1462
Initialize ``self``.
1463
1464
EXAMPLES::
1465
1466
sage: S = Set(QQ)
1467
sage: T = Set(ZZ)
1468
sage: X = S.symmetric_difference(T); X
1469
Set-theoretic symmetric difference of Set of elements of Rational Field and Set of elements of Integer Ring
1470
sage: latex(X)
1471
\Bold{Q} \bigtriangleup \Bold{Z}
1472
1473
sage: TestSuite(X).run()
1474
"""
1475
self.__X = X
1476
self.__Y = Y
1477
Set_object.__init__(self, self)
1478
1479
1480
def __cmp__(self, right):
1481
r"""
1482
Try to compare ``self`` and ``right``.
1483
1484
.. NOTE::
1485
1486
Comparison is basically not implemented, or rather it could
1487
say sets are not equal even though they are. I don't know
1488
how one could implement this for a generic symmetric
1489
difference of sets in a meaningful manner. So be careful
1490
when using this.
1491
1492
EXAMPLES::
1493
1494
sage: Y = Set(ZZ).symmetric_difference(Set(QQ))
1495
sage: X = Set(QQ).symmetric_difference(Set(ZZ))
1496
sage: X == Y
1497
True
1498
sage: Y == X
1499
True
1500
1501
"""
1502
if not is_Set(right):
1503
return -1
1504
if not isinstance(right, Set_object_symmetric_difference):
1505
return -1
1506
if self.__X == right.__X and self.__Y == right.__Y or \
1507
self.__X == right.__Y and self.__Y == right.__X:
1508
return 0
1509
return -1
1510
1511
def _repr_(self):
1512
"""
1513
Return string representation of ``self``.
1514
1515
EXAMPLES::
1516
1517
sage: X = Set(ZZ).symmetric_difference(Set(QQ)); X
1518
Set-theoretic symmetric difference of Set of elements of Integer Ring and Set of elements of Rational Field
1519
sage: X.rename('Z symdif Q')
1520
sage: X
1521
Z symdif Q
1522
"""
1523
return "Set-theoretic symmetric difference of %s and %s"%(self.__X,
1524
self.__Y)
1525
1526
def _latex_(self):
1527
r"""
1528
Return latex representation of ``self``.
1529
1530
EXAMPLES::
1531
1532
sage: X = Set(ZZ).symmetric_difference(Set(QQ))
1533
sage: latex(X)
1534
\Bold{Z} \bigtriangleup \Bold{Q}
1535
"""
1536
return '%s \\bigtriangleup %s'%(latex(self.__X), latex(self.__Y))
1537
1538
def __iter__(self):
1539
"""
1540
Return iterator through elements of ``self``.
1541
1542
This function is implemented by first iterating through the elements
1543
of `X` and yielding it if it is not in `Y`.
1544
Then it will iterate throw all the elements of `Y` and yielding it if
1545
it is not in `X`.
1546
1547
EXAMPLES::
1548
1549
sage: X = Set(ZZ).symmetric_difference(Primes())
1550
sage: I = X.__iter__()
1551
sage: I.next()
1552
0
1553
sage: I.next()
1554
1
1555
sage: I.next()
1556
-1
1557
sage: I.next()
1558
-2
1559
sage: I.next()
1560
-3
1561
"""
1562
for x in self.__X:
1563
if x not in self.__Y:
1564
yield x
1565
1566
for y in self.__Y:
1567
if y not in self.__X:
1568
yield y
1569
1570
1571
def __contains__(self, x):
1572
"""
1573
Return ``True`` if ``self`` contains ``x``.
1574
1575
Since ``self`` is the formal symmetric difference of `X` and `Y`
1576
this function returns ``True`` if either `X` or `Y` (but not both)
1577
contains ``x``.
1578
1579
EXAMPLES::
1580
1581
sage: X = Set(QQ).symmetric_difference(Primes())
1582
sage: 4 in X
1583
True
1584
sage: ComplexField().0 in X
1585
False
1586
sage: sqrt(2) in X # since sqrt(2) is currently symbolic
1587
False
1588
sage: sqrt(RR(2)) in X # since sqrt(RR(2)) is currently approximated
1589
True
1590
sage: pi in X
1591
False
1592
sage: 5/2 in X
1593
True
1594
sage: 3 in X
1595
False
1596
"""
1597
return (x in self.__X and x not in self.__Y) \
1598
or (x in self.__Y and x not in self.__X)
1599
1600
def cardinality(self):
1601
"""
1602
Try to return the cardinality of this formal symmetric difference.
1603
1604
..WARNING::
1605
1606
This is not likely to work in very much generality,
1607
and may just hang if either set involved is infinite.
1608
1609
EXAMPLES::
1610
1611
sage: X = Set(GF(13)).symmetric_difference(Set(range(5)))
1612
sage: X.cardinality()
1613
8
1614
"""
1615
return len(list(self))
1616
1617