-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathinterval.py
More file actions
2418 lines (2127 loc) · 78.6 KB
/
interval.py
File metadata and controls
2418 lines (2127 loc) · 78.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# from http://pypi.python.org/pypi/interval/1.0.0
"""Provides the Interval and IntervalSet classes
The interval module provides the Interval and IntervalSet data types.
Intervals describe continuous ranges that can be open, closed, half-open,
or infinite. IntervalSets contain zero to many disjoint sets of
Intervals.
Intervals don't have to pertain to numbers. They can contain any data
that is comparable via the Python operators <, <=, ==, >=, and >. Here's
an example of how strings can be used with Intervals:
>>> volume1 = Interval.between("A", "Foe")
>>> volume2 = Interval.between("Fog", "McAfee")
>>> volume3 = Interval.between("McDonalds", "Space")
>>> volume4 = Interval.between("Spade", "Zygote")
>>> encyclopedia = IntervalSet([volume1, volume2, volume3, volume4])
>>> mySet = IntervalSet([volume1, volume3, volume4])
>>> "Meteor" in encyclopedia
True
>>> "Goose" in encyclopedia
True
>>> "Goose" in mySet
False
>>> volume2 in (encyclopedia ^ mySet)
True
Here's an example of how times can be used with Intervals:
>>> officeHours = IntervalSet.between("08:00", "17:00")
>>> myLunch = IntervalSet.between("11:30", "12:30")
>>> myHours = IntervalSet.between("08:30", "19:30") - myLunch
>>> myHours.issubset(officeHours)
False
>>> "12:00" in myHours
False
>>> "15:30" in myHours
True
>>> inOffice = officeHours & myHours
>>> print inOffice
['08:30'..'11:30'),('12:30'..'17:00']
>>> overtime = myHours - officeHours
>>> print overtime
('17:00'..'19:30']
"""
import copy
class Smallest:
"""Represents the smallest value
This type doesn't do much; it implements a pseudo-value that's smaller
than everything but itself.
>>> negInf = Smallest()
>>> smallest = Smallest()
>>> -264 < negInf
False
>>> -264 == negInf
False
>>> -264 > negInf
True
>>> negInf < negInf
False
>>> negInf == smallest
True
"""
def __neg__(self):
"""Returns the largest value
The opposite of negative infinity is infinity, the largest value.
>>> print -Smallest()
~
"""
return Largest()
def __cmp__(self, other):
"""Compares this with another object
Always indicates that self is less than other, unless both are of
type Smallest, in which case they are equal.
>>> 0 < Smallest()
False
>>> -9999999 < Smallest()
False
>>> Smallest() < -9999999
True
>>> Smallest() < Smallest()
False
>>> Smallest() == Smallest()
True
"""
if other.__class__ == self.__class__:
retval = 0
else:
retval = -1
return retval
def __str__(self):
"""Returns a printable representation of this value
The string for the smallest number is -~, which means negative infinity.
>>> print Smallest()
-~
"""
return "-~"
def __repr__(self):
"""Returns an evaluable representation of the object
The representation of the smallest number is -Inf, which means
negative infinity.
>>> Smallest()
-Inf
"""
return "-Inf"
def __hash__(self):
"Returns a value that can be used for generating hashes"
return 0x55555555
class Largest:
"""Class representing the universal largest value
This type doesn't do much; it implements a pseudo-value that's larger
than everything but itself.
>>> infinity = Largest()
>>> greatest = Largest()
>>> 6234 < infinity
True
>>> 6234 == infinity
False
>>> 6234 > infinity
False
>>> infinity > infinity
False
>>> infinity == greatest
True
"""
def __neg__(self):
"""Returns the smallest universal value
The opposite of infinity is negative infinity, the smallest value.
>>> print -Largest()
-~
"""
return Smallest()
def __cmp__(self, other):
"""Compares object with another object
Always indicates that self is greater than other, unless both are of
type Largest, in which case they are equal.
>>> 0 > Largest()
False
>>> Largest() < 9999999
False
>>> Largest() > 9999999
True
>>> Largest() < Largest()
False
>>> Largest() == Largest()
True
"""
if other.__class__ == self.__class__:
retval = 0
else:
retval = 1
return retval
def __str__(self):
"""Returns a string representation of the object
The largest number is displayed as ~ (it sort of looks like infinity...)
>>> print Largest()
~
"""
return "~"
def __repr__(self):
"""Returns an evaluable expression representing this object
>>> Largest()
Inf
"""
return "Inf"
def __hash__(self):
"Returns a value that can be used for generating hashes"
return -0x55555555
Inf = Largest()
# Use -Inf for the smallest value
class Interval:
"""Represents a continuous range of values
An Interval is composed of the lower bound, a closed lower bound
flag, an upper bound, and a closed upper bound flag. The attributes
are called lower_bound, lower_closed, upper_bound, and upper_closed,
respectively. For an infinite interval, the bound is set to inf or
-inf. IntervalSets are composed of zero to many Intervals.
"""
def __init__(self, lower_bound=-Inf, upper_bound=Inf, **kwargs):
"""Initializes an interval
Parameters
==========
- lower_bound: The lower bound of an interval (default -Inf)
- upper_bound: The upper bound of an interval (default Inf)
- closed: Boolean telling whether both ends of the interval are closed
(default True). Setting this sets both lower_closed and upper_closed
- lower_closed: Boolean telling whether the lower end of the interval
is closed (default True)
- upper_closed: Boolean telling whether the upper end of the interval
is closed (default True)
An Interval can represent an infinite set.
>>> r = Interval(-Inf, Inf) # All values
An Interval can represent sets unbounded on an end.
>>> r = Interval(upper_bound=62, closed=False)
>>> r = Interval(upper_bound=37)
>>> r = Interval(lower_bound=246)
>>> r = Interval(lower_bound=2468, closed=False)
An Interval can represent a set of values up to, but not including a
value.
>>> r = Interval(25, 28, closed=False)
An Interval can represent a set of values that have an inclusive
boundary.
>>> r = Interval(29, 216)
An Interval can represent a single value
>>> r = Interval(82, 82)
Intervals that are not normalized, i.e. that have a lower bound
exceeding an upper bound, are silently normalized.
>>> print Interval(5, 2, lower_closed=False)
[2..5)
Intervals can represent an empty set.
>>> r = Interval(5, 5, closed=False)
Intervals can only contain hashable (immutable) objects.
>>> r = Interval([], 12)
Traceback (most recent call last):
...
TypeError: lower_bound is not hashable.
>>> r = Interval(12, [])
Traceback (most recent call last):
...
TypeError: upper_bound is not hashable.
"""
try:
h = hash(lower_bound)
except TypeError:
raise TypeError("lower_bound is not hashable.")
try:
h = hash(upper_bound)
except TypeError:
raise TypeError("upper_bound is not hashable.")
lower_closed = not (
isinstance(lower_bound, Smallest)
or isinstance(lower_bound, Largest)) \
and kwargs.get("lower_closed", kwargs.get("closed", True))
upper_closed = not (
isinstance(upper_bound, Smallest)
or isinstance(upper_bound, Largest)) \
and kwargs.get("upper_closed", kwargs.get("closed", True))
if upper_bound < lower_bound:
lower_bound, lower_closed, upper_bound, upper_closed = \
upper_bound, upper_closed, lower_bound, lower_closed
if ((lower_bound == -Inf) and lower_closed) \
or ((upper_bound == Inf) and upper_closed):
raise ValueError(
"Unbound ends cannot be included in an interval.")
self.lower_bound = lower_bound
self.lower_closed = lower_closed
self.upper_bound = upper_bound
self.upper_closed = upper_closed
def __hash__(self):
"""Returns a hashed value of the object
Intervals are to be considered immutable. Thus, a 32-bit hash can
be generated for them.
>>> h = hash(Interval.less_than(5))
"""
return hash((
self.lower_bound, self.lower_closed,
self.upper_bound, self.upper_closed))
def __repr__(self):
"""Returns an evaluable expression that can reproduce the object
>>> Interval(3, 6)
Interval(3, 6, lower_closed=True, upper_closed=True)
>>> Interval(3, 6, closed=False)
Interval(3, 6, lower_closed=False, upper_closed=False)
>>> Interval(3, 6, lower_closed=False)
Interval(3, 6, lower_closed=False, upper_closed=True)
>>> Interval()
Interval(-Inf, Inf, lower_closed=False, upper_closed=False)
"""
return "Interval(%s, %s, lower_closed=%s, upper_closed=%s)" % (
repr(self.lower_bound), repr(self.upper_bound),
self.lower_closed, self.upper_closed)
def __str__(self):
"""Returns a string representation of the object
This function yields a graphical representation of an Interval.
It is included in the __str__ of an IntervalSet. Non-inclusive
boundaries are bordered by a ( or ). Inclusive boundaries are
bordered by [ or ]. Unbound values are shown as .... Intervals
consisting of only a single value are shown as that value. Empty
intervals are shown as the string <Empty>
>>> print Interval.all()
(...)
>>> print Interval.less_than(100)
(...100)
>>> print Interval.less_than_or_equal_to(2593)
(...2593]
>>> print Interval.greater_than(2378)
(2378...)
>>> print Interval.between(26, 8234, False)
(26..8234)
>>> print Interval(237, 2348, lower_closed=False)
(237..2348]
>>> print Interval.greater_than_or_equal_to(347)
[347...)
>>> print Interval(237, 278, upper_closed=False)
[237..278)
>>> print Interval.between(723, 2378)
[723..2378]
>>> print Interval.equal_to(5)
5
>>> print Interval.none()
<Empty>
"""
if self.lower_bound == self.upper_bound:
if self.lower_closed or self.upper_closed:
retval = repr(self.lower_bound)
else:
retval = "<Empty>"
else:
between = ".."
if self.lower_closed:
lbchar = '['
else:
lbchar = '('
if self.lower_bound == -Inf:
lstr = ""
between = "..."
else:
lstr = repr(self.lower_bound)
if self.upper_closed:
ubchar = ']'
else:
ubchar = ')'
if self.upper_bound == Inf:
ustr = ""
between = "..."
else:
ustr = repr(self.upper_bound)
retval = "".join([lbchar, lstr, between, ustr, ubchar])
return retval
def __nonzero__(self):
"""Tells whether the interval is empty
>>> if Interval(12, 12, closed=False):
... print "Non-empty"
>>> if Interval(12, 12, upper_closed=False):
... print "Non-empty"
>>> if Interval(12, 12):
... print "Non-empty"
Non-empty
"""
return self.lower_bound != self.upper_bound \
or (self.upper_closed and self.lower_closed)
def __cmp__(self, other):
"""Compares two intervals for ordering purposes
>>> Interval.equal_to(-1) < Interval.equal_to(2)
True
>>> Interval.equal_to(-1) == Interval.equal_to(2)
False
>>> Interval.equal_to(-1) > Interval.equal_to(2)
False
>>> Interval.between(2, 5) > Interval.between(2, 4)
True
>>> Interval.between(2, 5) == Interval.between(2, 4)
False
>>> Interval.between(2, 5) == Interval.between(2, 5)
True
>>> Interval.between(2, 5) >= Interval.between(2, 5)
True
"""
if self == other:
result = 0
elif self.comes_before(other):
result = -1
else:
result = 1
return result
def __and__(self, other):
"""Returns the intersection of two intervals
>>> print Interval.greater_than(3) & Interval.greater_than(5)
(5...)
>>> print Interval.greater_than(3) & Interval.equal_to(3)
<Empty>
>>> print Interval.greater_than_or_equal_to(3) & Interval.equal_to(3)
3
>>> print Interval.all() & Interval.all()
(...)
>>> print Interval.greater_than(3) & Interval.less_than(10)
(3..10)
"""
if self == other:
result = Interval()
result.lower_bound = self.lower_bound
result.upper_bound = self.upper_bound
result.lower_closed = self.lower_closed
result.upper_closed = self.upper_closed
elif self.comes_before(other):
if self.overlaps(other):
if self.lower_bound == other.lower_bound:
lower = self.lower_bound
lower_closed = min(self.lower_closed, other.lower_closed)
elif self.lower_bound > other.lower_bound:
lower = self.lower_bound
lower_closed = self.lower_closed
else:
lower = other.lower_bound
lower_closed = other.lower_closed
if self.upper_bound == other.upper_bound:
upper = self.upper_bound
upper_closed = min(self.upper_closed, other.upper_closed)
elif self.upper_bound < other.upper_bound:
upper = self.upper_bound
upper_closed = self.upper_closed
else:
upper = other.upper_bound
upper_closed = other.upper_closed
result = Interval(
lower, upper,
lower_closed=lower_closed, upper_closed=upper_closed)
else:
result = Interval.none()
else:
result = other & self
return result
@classmethod
def none(cls):
"""Returns an empty interval
>>> print Interval.none()
<Empty>
"""
return cls(0, 0, closed=False)
@classmethod
def all(cls):
"""Returns an interval encompassing all values
>>> print Interval.all()
(...)
"""
return cls()
@classmethod
def between(cls, a, b, closed=True):
"""Returns an interval between two values
Returns an interval between values a and b. If closed is True,
then the endpoints are included. Otherwise, the endpoints are
excluded.
>>> print Interval.between(2, 4)
[2..4]
>>> print Interval.between(2, 4, False)
(2..4)
"""
return cls(a, b, closed=closed)
@classmethod
def equal_to(cls, a):
"""Returns an point interval
Returns an interval containing only a.
>>> print Interval.equal_to(32)
32
"""
return cls(a, a)
@classmethod
def less_than(cls, a):
"""Returns interval of all values less than the given value
Returns an interval containing all values less than a. If closed
is True, then all values less than or equal to a are returned.
>>> print Interval.less_than(32)
(...32)
"""
return cls(upper_bound=a, upper_closed=False)
@classmethod
def less_than_or_equal_to(cls, a):
"""Returns an interval containing the given values and everything less
>>> print Interval.less_than_or_equal_to(32)
(...32]
"""
return cls(upper_bound=a, upper_closed=True)
@classmethod
def greater_than(cls, a):
"""Returns interval of all values greater than the given value
>>> print Interval.greater_than(32)
(32...)
"""
return cls(lower_bound=a, lower_closed=False)
@classmethod
def greater_than_or_equal_to(cls, a):
"""Returns interval of all values greater than or equal to the given value
>>> print Interval.greater_than_or_equal_to(32)
[32...)
"""
return cls(lower_bound=a, lower_closed=True)
def comes_before(self, other):
"""Tells whether an interval lies before the object
self comes before other when sorted if its lower bound is less
than other's smallest value. If the smallest value is the same,
then the Interval with the smallest upper bound comes first.
Otherwise, they are equal.
>>> Interval.equal_to(1).comes_before(Interval.equal_to(4))
True
>>> Interval.less_than_or_equal_to(1).comes_before(Interval.equal_to(4))
True
>>> Interval.less_than_or_equal_to(5).comes_before(
... Interval.less_than(5))
False
>>> Interval.less_than(5).comes_before(
... Interval.less_than_or_equal_to(5))
True
>>> Interval.all().comes_before(Interval.all())
False
"""
if self == other:
result = False
elif self.lower_bound < other.lower_bound:
result = True
elif self.lower_bound > other.lower_bound:
result = False
elif self.lower_closed == other.lower_closed:
if self.upper_bound < other.upper_bound:
result = True
elif self.upper_bound > other.upper_bound \
or self.upper_closed == other.upper_closed \
or self.upper_closed:
result = False
else:
result = True
elif self.lower_closed:
result = True
else:
result = False
return result
def join(self, other):
"""Combines two continous Intervals
Combines two continuous Intervals into one Interval. If the two
Intervals are disjoint, then an exception is raised.
>>> r1 = Interval.less_than(-100)
>>> r2 = Interval.less_than_or_equal_to(-100)
>>> r3 = Interval.less_than(100)
>>> r4 = Interval.less_than_or_equal_to(100)
>>> r5 = Interval.all()
>>> r6 = Interval.between(-100, 100, False)
>>> r7 = Interval(-100, 100, lower_closed=False)
>>> r8 = Interval.greater_than(-100)
>>> r9 = Interval.equal_to(-100)
>>> r10 = Interval(-100, 100, upper_closed=False)
>>> r11 = Interval.between(-100, 100)
>>> r12 = Interval.greater_than_or_equal_to(-100)
>>> r13 = Interval.greater_than(100)
>>> r14 = Interval.equal_to(100)
>>> r15 = Interval.greater_than_or_equal_to(100)
>>> print r13.join(r15)
[100...)
>>> print r7.join(r6)
(-100..100]
>>> print r11.join(r2)
(...100]
>>> print r4.join(r15)
(...)
>>> print r8.join(r8)
(-100...)
>>> print r3.join(r7)
(...100]
>>> print r5.join(r10)
(...)
>>> print r9.join(r1)
(...-100]
>>> print r12.join(r5)
(...)
>>> print r13.join(r1)
Traceback (most recent call last):
...
ArithmeticError: The Intervals are disjoint.
>>> print r14.join(r2)
Traceback (most recent call last):
...
ArithmeticError: The Intervals are disjoint.
"""
if self.overlaps(other) or self.adjacent_to(other):
if self.lower_bound < other.lower_bound:
lbound = self.lower_bound
linc = self.lower_closed
elif self.lower_bound == other.lower_bound:
lbound = self.lower_bound
linc = max(self.lower_closed, other.lower_closed)
else:
lbound = other.lower_bound
linc = other.lower_closed
if self.upper_bound > other.upper_bound:
ubound = self.upper_bound
uinc = self.upper_closed
elif self.upper_bound == other.upper_bound:
ubound = self.upper_bound
uinc = max(self.upper_closed, other.upper_closed)
else:
ubound = other.upper_bound
uinc = other.upper_closed
return Interval(
lbound, ubound, upper_closed=uinc, lower_closed=linc)
else:
raise ArithmeticError("The Intervals are disjoint.")
def __contains__(self, obj):
"""Returns True if obj lies wholly within the Interval.
>>> all = Interval.all()
>>> lt = Interval.less_than(10)
>>> le = Interval.less_than_or_equal_to(10)
>>> some = Interval(10, 20, lower_closed=False)
>>> single = Interval.equal_to(10)
>>> ge = Interval.greater_than_or_equal_to(10)
>>> gt = Interval.greater_than(10)
>>> ne = Interval.equal_to(17)
>>> 10 in all
True
>>> 10 in lt
False
>>> 10 in le
True
>>> 10 in some
False
>>> 10 in single
True
>>> 10 in ge
True
>>> 10 in gt
False
>>> 10 in ne
False
>>> all in some
False
>>> lt in all
True
>>> lt in some
False
>>> single in ge
True
>>> ne in some
True
"""
if isinstance(obj, Interval):
if obj.lower_bound < self.lower_bound:
insideLower = False
elif obj.lower_bound == self.lower_bound:
insideLower = (obj.lower_closed <= self.lower_closed)
else:
insideLower = True
if obj.upper_bound > self.upper_bound:
insideUpper = False
elif obj.upper_bound == self.upper_bound:
insideUpper = (obj.upper_closed <= self.upper_closed)
else:
insideUpper = True
result = insideLower and insideUpper
else:
result = Interval.equal_to(obj) in self
return result
def overlaps(self, other):
"""Tells whether the given interval overlaps the object
Returns True if the one Interval overlaps another. If they are
immediately adjacent, then this returns False. Use the adjacent_to
function for testing for adjacent Intervals.
>>> r1 = Interval.less_than(-100)
>>> r2 = Interval.less_than_or_equal_to(-100)
>>> r3 = Interval.less_than(100)
>>> r4 = Interval.less_than_or_equal_to(100)
>>> r5 = Interval.all()
>>> r6 = Interval.between(-100, 100, False)
>>> r7 = Interval(-100, 100, lower_closed=False)
>>> r8 = Interval.greater_than(-100)
>>> r9 = Interval.equal_to(-100)
>>> r10 = Interval(-100, 100, upper_closed=False)
>>> r11 = Interval.between(-100, 100)
>>> r12 = Interval.greater_than_or_equal_to(-100)
>>> r13 = Interval.greater_than(100)
>>> r14 = Interval.equal_to(100)
>>> r15 = Interval.greater_than_or_equal_to(100)
>>> r8.overlaps(r9)
False
>>> r12.overlaps(r6)
True
>>> r7.overlaps(r8)
True
>>> r8.overlaps(r4)
True
>>> r14.overlaps(r11)
True
>>> r10.overlaps(r13)
False
>>> r5.overlaps(r1)
True
>>> r5.overlaps(r2)
True
>>> r15.overlaps(r6)
False
>>> r3.overlaps(r1)
True
"""
if self == other:
result = True
elif other.comes_before(self):
result = other.overlaps(self)
elif other.lower_bound < self.upper_bound:
result = True
elif other.lower_bound == self.upper_bound:
result = (other.lower_closed and self.upper_closed)
else:
result = False
return result
def adjacent_to(self, other):
"""Tells whether an Interval is adjacent to the object without overlap
Returns True if self is adjacent to other, meaning that if they
were joined, there would be no discontinuity. They cannot
overlap.
>>> r1 = Interval.less_than(-100)
>>> r2 = Interval.less_than_or_equal_to(-100)
>>> r3 = Interval.less_than(100)
>>> r4 = Interval.less_than_or_equal_to(100)
>>> r5 = Interval.all()
>>> r6 = Interval.between(-100, 100, False)
>>> r7 = Interval(-100, 100, lower_closed=False)
>>> r8 = Interval.greater_than(-100)
>>> r9 = Interval.equal_to(-100)
>>> r10 = Interval(-100, 100, upper_closed=False)
>>> r11 = Interval.between(-100, 100)
>>> r12 = Interval.greater_than_or_equal_to(-100)
>>> r13 = Interval.greater_than(100)
>>> r14 = Interval.equal_to(100)
>>> r15 = Interval.greater_than_or_equal_to(100)
>>> r1.adjacent_to(r6)
False
>>> r6.adjacent_to(r11)
False
>>> r7.adjacent_to(r9)
True
>>> r3.adjacent_to(r10)
False
>>> r5.adjacent_to(r14)
False
>>> r6.adjacent_to(r15)
True
>>> r1.adjacent_to(r8)
False
>>> r12.adjacent_to(r14)
False
>>> r6.adjacent_to(r13)
False
>>> r2.adjacent_to(r15)
False
>>> r1.adjacent_to(r4)
False
"""
if self.comes_before(other):
if self.upper_bound == other.lower_bound:
result = (self.upper_closed != other.lower_closed)
else:
result = False
elif self == other:
result = False
else:
result = other.adjacent_to(self)
return result
def __eq__(self, other):
"""Test if an interval is equivalent to the object
>>> Interval.all() == Interval.none()
False
>>> Interval.equal_to(4) == Interval(4, 4)
True
>>> Interval(2, 2, closed=False) == Interval(0, 0, closed=False)
True
"""
return (\
self.lower_bound == self.upper_bound and (\
not self.lower_closed or not self.upper_closed)\
and other.lower_bound == other.upper_bound and (\
not other.lower_closed or not other.upper_closed))\
or (\
self.lower_bound == other.lower_bound \
and self.upper_bound == other.upper_bound \
and self.lower_closed == other.lower_closed \
and self.upper_closed == other.upper_closed)
class BaseIntervalSet(object):
"Base class for IntervalSet and FrozenIntervalSet."
def __init__(self, items=[]):
"""Initializes a BaseIntervalSet
This function initializes an IntervalSet. It takes an iterable
object, such as a set, list, or generator. The elements returned
by the iterator are interpreted as intervals for Interval objects
and discrete values for all other values.
If no parameters are provided, then an empty IntervalSet is
constructed.
>>> print IntervalSet() # An empty set
<Empty>
Interval objects arguments are added directly to the IntervalSet.
>>> print IntervalSet([Interval(4, 6, lower_closed=False)])
(4..6]
>>> print IntervalSet([Interval.less_than_or_equal_to(2)])
(...2]
Each non-Interval value of an iterator is added as a discrete
value.
>>> print IntervalSet(set([3, 7, 2, 1]))
1,2,3,7
>>> print IntervalSet(["Bob", "Fred", "Mary"])
'Bob','Fred','Mary'
>>> print IntervalSet(range(10))
0,1,2,3,4,5,6,7,8,9
>>> print IntervalSet(
... Interval.between(l, u) for l, u in [(10, 20), (30, 40)])
[10..20],[30..40]
"""
self.intervals = []
for i in items:
self._add(i)
self.intervals.sort()
def __len__(self):
"""Returns the number of intervals contained in the object
>>> len(IntervalSet.empty())
0
>>> len(IntervalSet.all())
1
>>> len(IntervalSet([2, 6, 34]))
3
>>> len(IntervalSet.greater_than(0))
1
>>> nonempty = IntervalSet([3])
>>> if IntervalSet.empty():
... print "Non-empty"
>>> if nonempty:
... print "Non-empty"
Non-empty
"""
return len(self.intervals)
def __str__(self):
"""Returns a string representation of the object
This function shows a string representation of an IntervalSet.
The string is shown sorted, with all intervals normalized.
>>> print IntervalSet()
<Empty>
>>> print IntervalSet([62])
62
>>> print IntervalSet([62, 56])
56,62
>>> print IntervalSet([23, Interval(26, 32, upper_closed=False)])
23,[26..32)
>>> print IntervalSet.less_than(3) + IntervalSet.greater_than(3)
(...3),(3...)
>>> print IntervalSet([Interval.less_than_or_equal_to(6)])
(...6]
"""
if len(self.intervals) == 0:
rangeStr = "<Empty>"
else:
def sortFn(x, y):
if x.comes_before(y):
retval = -1
elif y.comes_before(x):
retval = 1
else:
retval = 0
return retval
rangeStr = ",".join([str(r) for r in self.intervals])
return rangeStr
def __getitem__(self, index):
"""Gets the interval at the given index
Unlike sets, which do not have ordering, BaseIntervalSets do. Therefore,
indexing was implemented. Intervals are stored in order, starting with
that with the left-most lower bound to that with the right-most.
>>> IntervalSet()[0]
Traceback (most recent call last):
...
IndexError: Index is out of range
>>> interval = IntervalSet.greater_than(5)
>>> print interval[0]
(5...)
>>> print interval[1]
Traceback (most recent call last):
...
IndexError: Index is out of range
>>> print interval[-1]
(5...)