# 2017-8-28 python interval 区间处理

Article Outline
``````>>> volume1 = Interval.between("A", "Foe")
>>> volume2 = Interval.between("Fog", "McAfee")
>>> volume3 = Interval.between("McDonalds", "Space")
>>> 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``````
``````a= 112
In [4]:  a in range(300,400)
...:
Out[4]: False
In [5]:  a in range(101,300)
...:
Out[5]: True ``````
``````python强大的区间处理库interval用法介绍

Interval类描述了一个连续的范围区间，这个区间可以是闭、开、半闭半开、无穷的，他的区间值不一定是数字，可以包含任何的数据类型，比如字符串，时间等等，同时他和python的各种操作（<, <=, ==, >=, >等）也是兼容的。IntervalSet包含了一个或多个互不相交的Interval集合。下面的这几个例子是源码中的。

>>>volume1 = Interval.between("A", "Foe")
>>>volume2 = Interval.between("Fog", "McAfee")
>>>volume3 = Interval.between("McDonalds", "Space")
>>>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

>>>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']

# coding
r1 = IntervalSet([Interval(1, 1000), Interval(1100, 1200)])
r2 = IntervalSet([Interval(30, 50), Interval(60, 200), Interval(1150, 1300)])

r3 = IntervalSet([Interval(1000, 3000)])
r4 = IntervalSet([Interval(1000, 3000)])
r5 = IntervalSet([Interval(30000, 12000)])

print (r3 - r4), (r4 - r3), r3 & r4
print len(IntervalSet.empty())

if r3 & r4 == r4:
print 'yes'

print r3 & r4
if (r3 - r4).empty():
print "true"
print (r3 - r4).empty()

# output
<Empty> <Empty> [1000..3000]
0
yes
[1000..3000]
<Empty>

interval对象初始化参数（lower_bound=-Inf, upper_bound=Inf, **kwargs）三个boolean参数closed,lower_closed,upper_closed分表表示全闭，左闭右开，左开右闭。比如：r = Interval(upper_bound=62, closed=False)
between(a, b, closed=True)：返回以a和b为界的区间
less_than(a)：小于a的所有值构成interval，类似的还有less_than_or_equal_to，greater_than，greater_than_or_equal_to函数
join(other)：将两个连续的intervals组合起来
overlaps(other)：两个区间是否有重叠