开发者

Is there a discontinuous range class for Python?

开发者 https://www.devze.com 2023-03-29 07:48 出处:网络
I\'d like to represent an arbitrarily complex range of real values, which can be discontinuous, i.e.:

I'd like to represent an arbitrarily complex range of real values, which can be discontinuous, i.e.:

0--4 and 5--6 and 7.12423--8

Where I'll be adding new ranges incrementally:

(0--4 and 5--6 and 7.12423--8) | ( 2--7) = (0--7 and 7.12423--8)

I don't really know the right language to describe this, so开发者_运维技巧 I'm struggling to search, but it seems like a class probably already exists to do what I want to do. Does it?


There are at least a couple of packages listed in the Python Package Index which deal with intervals:

  • interval

  • pyinterval

I've experimented with interval before and found it to be well-written and documented (at the moment its website seems to be unavailable). I've not used pyinterval.


In addition to the interval and pyinterval packages mentioned by Ned, there is also pyinter.

As pyinterval didn't compile on my machine, I only played with interval and pyinter.

The former seems better to me, because it has addition and subtraction operators defined for interval sets, which pyinter has not. Also when I tried to calculate the union of two discrete points, it worked as expected in interval, but raised AttributeError ("'int' object has no attribute 'overlaps'") in pyinter.

One very visible difference of pyinter was the the __repr__ function of the interval class which would output (7,9] instead of Interval(7, 9, lower_closed=False, upper_closed=True) (the latter is the representation of the interval package). While this is nice for quick interactive work, closed intervals might be confunded with two-element lists. Here I also like the interval package's approach more: It has a less ambiguous representation, but additionally defines a __str__ method, so that when calling str() or print() on the example interval, it would output as (7..9].

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号