Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/structure/sequence.py
4036 views
1
r"""
2
Sequences
3
4
A mutable sequence of elements with a common guaranteed category,
5
which can be set immutable.
6
7
Sequence derives from list, so has all the functionality of lists and
8
can be used wherever lists are used. When a sequence is created
9
without explicitly given the common universe of the elements, the
10
constructor coerces the first and second element to some
11
*canonical* common parent, if possible, then the second and
12
third, etc. If this is possible, it then coerces everything into the
13
canonical parent at the end. (Note that canonical coercion is very
14
restrictive.) The sequence then has a function ``universe()``
15
which returns either the common canonical parent (if the coercion
16
succeeded), or the category of all objects (Objects()). So if you
17
have a list `v` and type
18
19
sage: v = [1, 2/3, 5]
20
sage: w = Sequence(v)
21
sage: w.universe()
22
Rational Field
23
24
then since ``w.universe()`` is `\QQ`, you're guaranteed that all
25
elements of `w` are rationals:
26
27
sage: v[0].parent()
28
Integer Ring
29
sage: w[0].parent()
30
Rational Field
31
32
If you do assignment to `w` this property of being rationals is guaranteed
33
to be preserved.
34
35
sage: w[0] = 2
36
sage: w[0].parent()
37
Rational Field
38
sage: w[0] = 'hi'
39
Traceback (most recent call last):
40
...
41
TypeError: unable to convert hi to a rational
42
43
However, if you do ``w = Sequence(v)`` and the resulting universe
44
is ``Objects()``, the elements are not guaranteed to have any
45
special parent. This is what should happen, e.g., with finite field
46
elements of different characteristics::
47
48
sage: v = Sequence([GF(3)(1), GF(7)(1)])
49
sage: v.universe()
50
Category of objects
51
52
You can make a list immutable with ``v.freeze()``. Assignment is
53
never again allowed on an immutable list.
54
55
Creation of a sequence involves making a copy of the input list, and
56
substantial coercions. It can be greatly sped up by explicitly
57
specifying the universe of the sequence::
58
59
sage: v = Sequence(range(10000), universe=ZZ)
60
61
TESTS::
62
63
sage: v = Sequence([1..5])
64
sage: loads(dumps(v)) == v
65
True
66
67
"""
68
69
70
##########################################################################
71
#
72
# Sage: System for Algebra and Geometry Experimentation
73
#
74
# Copyright (C) 2006 William Stein <[email protected]>
75
#
76
# Distributed under the terms of the GNU General Public License (GPL)
77
# http://www.gnu.org/licenses/
78
##########################################################################
79
80
81
from sage.misc.latex import list_function as list_latex_function
82
import sage.structure.sage_object
83
84
#from mutability import Mutability #we cannot inherit from Mutability and list at the same time
85
86
def Sequence(x, universe=None, check=True, immutable=False, cr=False, cr_str=None, use_sage_types=False):
87
"""
88
A mutable list of elements with a common guaranteed universe,
89
which can be set immutable.
90
91
A universe is either an object that supports coercion (e.g., a
92
parent), or a category.
93
94
INPUT:
95
96
- ``x`` - a list or tuple instance
97
98
- ``universe`` - (default: None) the universe of elements; if None
99
determined using canonical coercions and the entire list of
100
elements. If list is empty, is category Objects() of all
101
objects.
102
103
- ``check`` -- (default: True) whether to coerce the elements of x
104
into the universe
105
106
- ``immutable`` - (default: True) whether or not this sequence is
107
immutable
108
109
- ``cr`` - (default: False) if True, then print a carriage return
110
after each comma when printing this sequence.
111
112
- ``cr_str`` - (default: False) if True, then print a carriage return
113
after each comma when calling ``str()`` on this sequence.
114
115
- ``use_sage_types`` -- (default: False) if True, coerce the
116
built-in Python numerical types int, long, float, complex to the
117
corresponding Sage types (this makes functions like vector()
118
more flexible)
119
120
OUTPUT:
121
122
- a sequence
123
124
EXAMPLES::
125
126
sage: v = Sequence(range(10))
127
sage: v.universe()
128
<type 'int'>
129
sage: v
130
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
131
132
We can request that the built-in Python numerical types be coerced
133
to Sage objects::
134
135
sage: v = Sequence(range(10), use_sage_types=True)
136
sage: v.universe()
137
Integer Ring
138
sage: v
139
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
140
141
You can also use seq for "Sequence", which is identical to using
142
Sequence::
143
144
sage: v = seq([1,2,1/1]); v
145
[1, 2, 1]
146
sage: v.universe()
147
Rational Field
148
sage: v.parent()
149
Category of sequences in Rational Field
150
sage: v.parent()([3,4/3])
151
[3, 4/3]
152
153
154
Note that assignment coerces if possible,::
155
156
sage: v = Sequence(range(10), ZZ)
157
sage: a = QQ(5)
158
sage: v[3] = a
159
sage: parent(v[3])
160
Integer Ring
161
sage: parent(a)
162
Rational Field
163
sage: v[3] = 2/3
164
Traceback (most recent call last):
165
...
166
TypeError: no conversion of this rational to integer
167
168
Sequences can be used absolutely anywhere lists or tuples can be used::
169
170
sage: isinstance(v, list)
171
True
172
173
Sequence can be immutable, so entries can't be changed::
174
175
sage: v = Sequence([1,2,3], immutable=True)
176
sage: v.is_immutable()
177
True
178
sage: v[0] = 5
179
Traceback (most recent call last):
180
...
181
ValueError: object is immutable; please change a copy instead.
182
183
Only immutable sequences are hashable (unlike Python lists),
184
though the hashing is potentially slow, since it first involves
185
conversion of the sequence to a tuple, and returning the hash of
186
that.::
187
188
sage: v = Sequence(range(10), ZZ, immutable=True)
189
sage: hash(v)
190
1591723448 # 32-bit
191
-4181190870548101704 # 64-bit
192
193
194
If you really know what you are doing, you can circumvent the type
195
checking (for an efficiency gain)::
196
197
sage: list.__setitem__(v, int(1), 2/3) # bad circumvention
198
sage: v
199
[0, 2/3, 2, 3, 4, 5, 6, 7, 8, 9]
200
sage: list.__setitem__(v, int(1), int(2)) # not so bad circumvention
201
202
You can make a sequence with a new universe from an old sequence.::
203
204
sage: w = Sequence(v, QQ)
205
sage: w
206
[0, 2, 2, 3, 4, 5, 6, 7, 8, 9]
207
sage: w.universe()
208
Rational Field
209
sage: w[1] = 2/3
210
sage: w
211
[0, 2/3, 2, 3, 4, 5, 6, 7, 8, 9]
212
213
Sequences themselves live in a category, the category of all sequences
214
in the given universe.::
215
216
sage: w.category()
217
Category of sequences in Rational Field
218
219
This is also the parent of any sequence::
220
221
sage: w.parent()
222
Category of sequences in Rational Field
223
224
The default universe for any sequence, if no compatible parent structure
225
can be found, is the universe of all Sage objects.
226
227
This example illustrates how every element of a list is taken into account
228
when constructing a sequence.::
229
230
sage: v = Sequence([1,7,6,GF(5)(3)]); v
231
[1, 2, 1, 3]
232
sage: v.universe()
233
Finite Field of size 5
234
sage: v.parent()
235
Category of sequences in Finite Field of size 5
236
sage: v.parent()([7,8,9])
237
[2, 3, 4]
238
"""
239
from sage.rings.polynomial.multi_polynomial_ideal import MPolynomialIdeal
240
241
242
if isinstance(x, Sequence_generic) and universe is None:
243
universe = x.universe()
244
x = list(x)
245
246
if isinstance(x, MPolynomialIdeal) and universe is None:
247
universe = x.ring()
248
x = x.gens()
249
250
if universe is None:
251
if not isinstance(x, (list, tuple)):
252
x = list(x)
253
#raise TypeError("x must be a list or tuple")
254
255
if len(x) == 0:
256
import sage.categories.all
257
universe = sage.categories.all.Objects()
258
else:
259
import sage.structure.element as coerce
260
y = x
261
x = list(x) # make a copy, or we'd change the type of the elements of x, which would be bad.
262
if use_sage_types:
263
# convert any Python built-in numerical types to Sage objects
264
from sage.rings.integer_ring import ZZ
265
from sage.rings.real_double import RDF
266
from sage.rings.complex_double import CDF
267
for i in range(len(x)):
268
if isinstance(x[i], int) or isinstance(x[i], long):
269
x[i] = ZZ(x[i])
270
elif isinstance(x[i], float):
271
x[i] = RDF(x[i])
272
elif isinstance(x[i], complex):
273
x[i] = CDF(x[i])
274
# start the pairwise coercion
275
for i in range(len(x)-1):
276
try:
277
x[i], x[i+1] = coerce.canonical_coercion(x[i],x[i+1])
278
except TypeError:
279
import sage.categories.all
280
universe = sage.categories.all.Objects()
281
x = list(y)
282
check = False # no point
283
break
284
if universe is None: # no type errors raised.
285
universe = coerce.parent(x[len(x)-1])
286
287
from sage.rings.polynomial.multi_polynomial_ring import is_MPolynomialRing
288
from sage.rings.quotient_ring import is_QuotientRing
289
from sage.rings.polynomial.pbori import BooleanMonomialMonoid
290
291
if is_MPolynomialRing(universe) or \
292
(is_QuotientRing(universe) and is_MPolynomialRing(universe.cover_ring())) or \
293
isinstance(universe, BooleanMonomialMonoid):
294
from sage.rings.polynomial.multi_polynomial_sequence import PolynomialSequence
295
try:
296
return PolynomialSequence(x, universe, immutable=immutable, cr=cr, cr_str=cr_str)
297
except (TypeError,AttributeError):
298
return Sequence_generic(x, universe, check, immutable, cr, cr_str, use_sage_types)
299
else:
300
return Sequence_generic(x, universe, check, immutable, cr, cr_str, use_sage_types)
301
302
class Sequence_generic(sage.structure.sage_object.SageObject, list):
303
"""
304
A mutable list of elements with a common guaranteed universe,
305
which can be set immutable.
306
307
A universe is either an object that supports coercion (e.g., a parent),
308
or a category.
309
310
INPUT:
311
312
- ``x`` - a list or tuple instance
313
314
- ``universe`` - (default: None) the universe of elements; if None
315
determined using canonical coercions and the entire list of
316
elements. If list is empty, is category Objects() of all
317
objects.
318
319
- ``check`` -- (default: True) whether to coerce the elements of x
320
into the universe
321
322
- ``immutable`` - (default: True) whether or not this sequence is
323
immutable
324
325
- ``cr`` - (default: False) if True, then print a carriage return
326
after each comma when printing this sequence.
327
328
- ``use_sage_types`` -- (default: False) if True, coerce the
329
built-in Python numerical types int, long, float, complex to the
330
corresponding Sage types (this makes functions like vector()
331
more flexible)
332
333
OUTPUT:
334
335
- a sequence
336
337
EXAMPLES::
338
339
sage: v = Sequence(range(10))
340
sage: v.universe()
341
<type 'int'>
342
sage: v
343
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
344
345
We can request that the built-in Python numerical types be coerced
346
to Sage objects::
347
348
sage: v = Sequence(range(10), use_sage_types=True)
349
sage: v.universe()
350
Integer Ring
351
sage: v
352
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
353
354
You can also use seq for "Sequence", which is identical to using Sequence::
355
356
sage: v = seq([1,2,1/1]); v
357
[1, 2, 1]
358
sage: v.universe()
359
Rational Field
360
sage: v.parent()
361
Category of sequences in Rational Field
362
sage: v.parent()([3,4/3])
363
[3, 4/3]
364
365
366
Note that assignment coerces if possible,
367
368
::
369
370
sage: v = Sequence(range(10), ZZ)
371
sage: a = QQ(5)
372
sage: v[3] = a
373
sage: parent(v[3])
374
Integer Ring
375
sage: parent(a)
376
Rational Field
377
sage: v[3] = 2/3
378
Traceback (most recent call last):
379
...
380
TypeError: no conversion of this rational to integer
381
382
Sequences can be used absolutely anywhere lists or tuples can be used::
383
384
sage: isinstance(v, list)
385
True
386
387
Sequence can be immutable, so entries can't be changed::
388
389
sage: v = Sequence([1,2,3], immutable=True)
390
sage: v.is_immutable()
391
True
392
sage: v[0] = 5
393
Traceback (most recent call last):
394
...
395
ValueError: object is immutable; please change a copy instead.
396
397
Only immutable sequences are hashable (unlike Python lists),
398
though the hashing is potentially slow, since it first involves
399
conversion of the sequence to a tuple, and returning the hash of
400
that.
401
402
::
403
404
sage: v = Sequence(range(10), ZZ, immutable=True)
405
sage: hash(v)
406
1591723448 # 32-bit
407
-4181190870548101704 # 64-bit
408
409
410
If you really know what you are doing, you can circumvent the type
411
checking (for an efficiency gain)::
412
413
sage: list.__setitem__(v, int(1), 2/3) # bad circumvention
414
sage: v
415
[0, 2/3, 2, 3, 4, 5, 6, 7, 8, 9]
416
sage: list.__setitem__(v, int(1), int(2)) # not so bad circumvention
417
418
You can make a sequence with a new universe from an old sequence.
419
420
::
421
422
sage: w = Sequence(v, QQ)
423
sage: w
424
[0, 2, 2, 3, 4, 5, 6, 7, 8, 9]
425
sage: w.universe()
426
Rational Field
427
sage: w[1] = 2/3
428
sage: w
429
[0, 2/3, 2, 3, 4, 5, 6, 7, 8, 9]
430
431
Sequences themselves live in a category, the category of all sequences
432
in the given universe.
433
434
::
435
436
sage: w.category()
437
Category of sequences in Rational Field
438
439
This is also the parent of any sequence::
440
441
sage: w.parent()
442
Category of sequences in Rational Field
443
444
The default universe for any sequence, if no compatible parent structure
445
can be found, is the universe of all Sage objects.
446
447
This example illustrates how every element of a list is taken into account
448
when constructing a sequence.
449
450
::
451
452
sage: v = Sequence([1,7,6,GF(5)(3)]); v
453
[1, 2, 1, 3]
454
sage: v.universe()
455
Finite Field of size 5
456
sage: v.parent()
457
Category of sequences in Finite Field of size 5
458
sage: v.parent()([7,8,9])
459
[2, 3, 4]
460
461
462
"""
463
def __init__(self, x, universe=None, check=True, immutable=False,
464
cr=False, cr_str=None, use_sage_types=False):
465
"""
466
Create a sequence.
467
468
EXAMPLES::
469
470
sage: Sequence([1..5])
471
[1, 2, 3, 4, 5]
472
sage: a = Sequence([1..3], universe=QQ, check=False, immutable=True, cr=True, cr_str=False, use_sage_types=True)
473
sage: a
474
[
475
1,
476
2,
477
3
478
]
479
sage: a = Sequence([1..5], universe=QQ, check=False, immutable=True, cr_str=True, use_sage_types=True)
480
sage: a
481
[1, 2, 3, 4, 5]
482
sage: a._Sequence_generic__cr_str
483
True
484
sage: a.__str__()
485
'[\n1,\n2,\n3,\n4,\n5\n]'
486
"""
487
self.__hash = None
488
489
self.__cr = cr
490
if cr_str is None:
491
self.__cr_str = cr
492
else:
493
self.__cr_str = cr_str
494
495
if isinstance(x, Sequence_generic):
496
if universe is None or universe == x.__universe:
497
list.__init__(self, x)
498
self.__universe = x.__universe
499
self._is_immutable = immutable
500
return
501
502
self.__universe = universe
503
if check:
504
x = [universe(t) for t in x]
505
list.__init__(self, x)
506
self._is_immutable = immutable
507
508
def reverse(self):
509
"""
510
Reverse the elements of self, in place.
511
512
EXAMPLES::
513
514
sage: B = Sequence([1,2,3])
515
sage: B.reverse(); B
516
[3, 2, 1]
517
"""
518
self._require_mutable()
519
list.reverse(self)
520
521
def __setitem__(self, n, value):
522
"""
523
EXAMPLES::
524
525
sage: a = Sequence([1..5])
526
sage: a[2] = 19
527
sage: a
528
[1, 2, 19, 4, 5]
529
sage: a[2] = 'hello'
530
Traceback (most recent call last):
531
...
532
TypeError: unable to convert x (=hello) to an integer
533
sage: a[2] = '5'
534
sage: a
535
[1, 2, 5, 4, 5]
536
sage: v = Sequence([1,2,3,4], immutable=True)
537
sage: v[1:3] = [5,7]
538
Traceback (most recent call last):
539
...
540
ValueError: object is immutable; please change a copy instead.
541
sage: v = Sequence([1,2,3,4])
542
sage: v[1:3] = [5, 3/1]
543
sage: v
544
[1, 5, 3, 4]
545
sage: type(v[2])
546
<type 'sage.rings.integer.Integer'>
547
"""
548
self._require_mutable()
549
if isinstance(n, slice):
550
y = [self.__universe(x) for x in value]
551
else:
552
y = self.__universe(value)
553
list.__setitem__(self, n, y)
554
self.__hash=None
555
556
def __getitem__(self, n):
557
"""
558
EXAMPLES::
559
560
sage: v = Sequence([1,2,3,4], immutable=True)
561
sage: w = v[2:]
562
sage: w
563
[3, 4]
564
sage: type(w)
565
<class 'sage.structure.sequence.Sequence_generic'>
566
sage: w[0] = 5; w
567
[5, 4]
568
sage: v
569
[1, 2, 3, 4]
570
"""
571
if isinstance(n, slice):
572
return Sequence(list.__getitem__(self, n),
573
universe = self.__universe,
574
check = False,
575
immutable = False,
576
cr = self.__cr)
577
else:
578
return list.__getitem__(self,n)
579
580
# We have to define the *slice functions as long as Sage uses Python 2.*
581
# otherwise the inherited *slice functions from list are called
582
def __getslice__(self, i, j):
583
return self.__getitem__(slice(i,j))
584
585
def __setslice__(self, i, j, value):
586
return self.__setitem__(slice(i,j), value)
587
588
def append(self, x):
589
"""
590
EXAMPLES:
591
sage: v = Sequence([1,2,3,4], immutable=True)
592
sage: v.append(34)
593
Traceback (most recent call last):
594
...
595
ValueError: object is immutable; please change a copy instead.
596
sage: v = Sequence([1/3,2,3,4])
597
sage: v.append(4)
598
sage: type(v[4])
599
<type 'sage.rings.rational.Rational'>
600
"""
601
self._require_mutable()
602
y = self.__universe(x)
603
list.append(self, y)
604
605
def extend(self, iterable):
606
"""
607
Extend list by appending elements from the iterable.
608
609
EXAMPLES::
610
611
sage: B = Sequence([1,2,3])
612
sage: B.extend(range(4))
613
sage: B
614
[1, 2, 3, 0, 1, 2, 3]
615
"""
616
self._require_mutable()
617
v = [self.__universe(x) for x in iterable]
618
list.extend(self, v)
619
620
def insert(self, index, object):
621
"""
622
Insert object before index.
623
624
EXAMPLES::
625
626
sage: B = Sequence([1,2,3])
627
sage: B.insert(10, 5)
628
sage: B
629
[1, 2, 3, 5]
630
"""
631
self._require_mutable()
632
list.insert(self, index, self.__universe(object))
633
634
def pop(self, index=-1):
635
"""
636
Remove and return item at index (default last)
637
638
EXAMPLES::
639
640
sage: B = Sequence([1,2,3])
641
sage: B.pop(1)
642
2
643
sage: B
644
[1, 3]
645
"""
646
self._require_mutable()
647
return list.pop(self, index)
648
649
def remove(self, value):
650
"""
651
Remove first occurrence of value
652
653
EXAMPLES::
654
655
sage: B = Sequence([1,2,3])
656
sage: B.remove(2)
657
sage: B
658
[1, 3]
659
"""
660
self._require_mutable()
661
list.remove(self, value)
662
663
def sort(self, cmp=None, key=None, reverse=False):
664
"""
665
Sort this list *IN PLACE*.
666
667
cmp(x, y) -> -1, 0, 1
668
669
EXAMPLES::
670
671
sage: B = Sequence([3,2,1/5])
672
sage: B.sort()
673
sage: B
674
[1/5, 2, 3]
675
sage: B.sort(reverse=True); B
676
[3, 2, 1/5]
677
sage: B.sort(cmp = lambda x,y: cmp(y,x)); B
678
[3, 2, 1/5]
679
sage: B.sort(cmp = lambda x,y: cmp(y,x), reverse=True); B
680
[1/5, 2, 3]
681
"""
682
self._require_mutable()
683
list.sort(self, cmp=cmp, key=key, reverse=reverse)
684
685
def __hash__(self):
686
"""
687
EXAMPLES::
688
689
sage: a = Sequence([1..5])
690
sage: a.__hash__()
691
Traceback (most recent call last):
692
...
693
ValueError: mutable sequences are unhashable
694
sage: a[0] = 10
695
sage: a.set_immutable()
696
sage: a.__hash__()
697
-123014399 # 32-bit
698
-5823618793256324351 # 64-bit
699
sage: hash(a)
700
-123014399 # 32-bit
701
-5823618793256324351 # 64-bit
702
"""
703
if not self._is_immutable:
704
raise ValueError("mutable sequences are unhashable")
705
if self.__hash is None:
706
self.__hash = hash(tuple(self))
707
return self.__hash
708
709
def _repr_(self):
710
"""
711
EXAMPLES::
712
713
sage: Sequence([1,2/3,-2/5])._repr_()
714
'[1, 2/3, -2/5]'
715
sage: print Sequence([1,2/3,-2/5], cr=True)._repr_()
716
[
717
1,
718
2/3,
719
-2/5
720
]
721
"""
722
if self.__cr:
723
return '[\n' + ',\n'.join([repr(x) for x in self]) + '\n]'
724
else:
725
return list.__repr__(self)
726
727
def _latex_(self):
728
r"""
729
TESTS::
730
731
sage: t= Sequence([sqrt(x), exp(x), x^(x-1)], universe=SR); t
732
[sqrt(x), e^x, x^(x - 1)]
733
sage: t._latex_()
734
'\\left[\\sqrt{x}, e^{x}, x^{x - 1}\\right]'
735
sage: latex(t)
736
\left[\sqrt{x}, e^{x}, x^{x - 1}\right]
737
"""
738
return list_latex_function(self)
739
740
def __str__(self):
741
"""
742
EXAMPLES::
743
744
sage: s = Sequence([1,2,3], cr=False)
745
sage: str(s)
746
'[1, 2, 3]'
747
sage: repr(s)
748
'[1, 2, 3]'
749
sage: print s
750
[1, 2, 3]
751
sage: s = Sequence([1,2,3], cr=True)
752
sage: str(s)
753
'[\n1,\n2,\n3\n]'
754
"""
755
if self.__cr_str:
756
return '[\n' + ',\n'.join([str(x) for x in self]) + '\n]'
757
else:
758
return list.__str__(self)
759
760
def category(self):
761
"""
762
EXAMPLES::
763
764
sage: Sequence([1,2/3,-2/5]).category()
765
Category of sequences in Rational Field
766
"""
767
import sage.categories.all
768
return sage.categories.all.Sequences(self.universe())
769
770
def parent(self):
771
"""
772
773
EXAMPLES::
774
775
sage: Sequence([1,2/3,-2/5]).parent()
776
Category of sequences in Rational Field
777
"""
778
return self.category()
779
780
def universe(self):
781
"""
782
EXAMPLES::
783
784
sage: Sequence([1,2/3,-2/5]).universe()
785
Rational Field
786
sage: Sequence([1,2/3,'-2/5']).universe()
787
Category of objects
788
"""
789
return self.__universe
790
791
def _require_mutable(self):
792
"""
793
EXAMPLES::
794
795
sage: a = Sequence([1,2/3,'-2/5'])
796
sage: a._require_mutable()
797
sage: a.set_immutable()
798
sage: a._require_mutable()
799
Traceback (most recent call last):
800
...
801
ValueError: object is immutable; please change a copy instead.
802
"""
803
if self._is_immutable:
804
raise ValueError("object is immutable; please change a copy instead.")
805
806
def set_immutable(self):
807
"""
808
Make this object immutable, so it can never again be changed.
809
810
EXAMPLES::
811
812
sage: v = Sequence([1,2,3,4/5])
813
sage: v[0] = 5
814
sage: v
815
[5, 2, 3, 4/5]
816
sage: v.set_immutable()
817
sage: v[3] = 7
818
Traceback (most recent call last):
819
...
820
ValueError: object is immutable; please change a copy instead.
821
"""
822
self._is_immutable = True
823
824
def is_immutable(self):
825
"""
826
Return True if this object is immutable (can not be changed)
827
and False if it is not.
828
829
To make this object immutable use :meth:`set_immutable`.
830
831
EXAMPLE::
832
833
sage: v = Sequence([1,2,3,4/5])
834
sage: v[0] = 5
835
sage: v
836
[5, 2, 3, 4/5]
837
sage: v.is_immutable()
838
False
839
sage: v.set_immutable()
840
sage: v.is_immutable()
841
True
842
"""
843
try:
844
return self._is_immutable
845
except AttributeError:
846
return False
847
848
def is_mutable(self):
849
"""
850
EXAMPLES::
851
852
sage: a = Sequence([1,2/3,-2/5])
853
sage: a.is_mutable()
854
True
855
sage: a[0] = 100
856
sage: type(a[0])
857
<type 'sage.rings.rational.Rational'>
858
sage: a.set_immutable()
859
sage: a[0] = 50
860
Traceback (most recent call last):
861
...
862
ValueError: object is immutable; please change a copy instead.
863
sage: a.is_mutable()
864
False
865
"""
866
try:
867
return not self._is_immutable
868
except AttributeError:
869
return True
870
871
872
def __copy__(self):
873
"""
874
Return a copy of this sequence
875
876
EXAMPLES::
877
878
sage: s = seq(range(10))
879
sage: t = copy(s)
880
sage: t == s
881
True
882
sage: t.is_immutable == s.is_immutable
883
True
884
sage: t.is_mutable == s.is_mutable
885
True
886
sage: t.parent() == s.parent()
887
True
888
889
"""
890
return Sequence(self,universe = self.__universe,
891
check = False,
892
immutable = self._is_immutable,
893
cr = self.__cr_str)
894
895
def __getattr__(self, name):
896
"""
897
Strictly for unpickling old 'Sequences'
898
899
INPUT:
900
901
- ``name`` - some string
902
903
TESTS::
904
905
sage: S = Sequence([])
906
sage: del S._Sequence_generic__universe
907
sage: S.universe()
908
Traceback (most recent call last):
909
...
910
AttributeError: 'Sequence_generic' object has no attribute '_Sequence_generic__universe'
911
sage: S._Sequence__universe = 'foobar'
912
sage: S.universe()
913
'foobar'
914
"""
915
if name == "_Sequence_generic__cr" and hasattr(self,"_Sequence__cr"):
916
self.__cr = self._Sequence__cr
917
return self.__cr
918
elif name == "_Sequence_generic__cr_str" and hasattr(self,"_Sequence__cr_str"):
919
self.__cr_str = self._Sequence__cr_str
920
return self.__cr_str
921
elif name == "_Sequence_generic__immutable" and hasattr(self,"_Sequence__immutable"):
922
self.__immutable = self._Sequence__immutable
923
return self.__immutable
924
elif name == "_Sequence_generic__universe" and hasattr(self,"_Sequence__universe"):
925
self.__universe = self._Sequence__universe
926
return self.__universe
927
else:
928
raise AttributeError("'Sequence_generic' object has no attribute '%s'"%name)
929
seq = Sequence
930
931
from sage.structure.sage_object import register_unpickle_override
932
register_unpickle_override('sage.structure.sequence', 'Sequence', Sequence_generic)
933
934