How to check if a number is in an interval
Suppose I got:
first_var = 1
second_var = 5
interval = 2
I need an interval from second_var like second_var ± interval
(3 to 7). I decided to check if first_var is in this interval. So in this particular case I want False
If first_var = 4
, I wantTrue
I can do it:
if (first_var > second_var-interval) and (first_var < second_var+interval):
#True
Is there a more pythonic way to do this?
source to share
I am using class c __contains__
to represent an interval:
class Interval(object):
def __init__(self, middle, deviation):
self.lower = middle - abs(deviation)
self.upper = middle + abs(deviation)
def __contains__(self, item):
return self.lower <= item <= self.upper
Then I define a function interval
to simplify the syntax:
def interval(middle, deviation):
return Interval(middle, deviation)
Then we can call it like this:
>>> 8 in interval(middle=6, deviation=2)
True
>>> 8 in interval(middle=6, deviation=1)
False
As of Python 2, this solution is more efficient than using range
or xrange
as they don't implement __contains__
and they have to look for a suitable value.
Python 3 is smarter, and range
is a generating object that is efficient as xrange
but also implements __contains__
so it doesn't need to look for a valid value. xrange
doesn't exist in Python 3.
This solution also works with floats.
Also, note that if you are using range
, you need to be careful with one-by-one errors. Better to encapsulate it if you are going to do it more than once or twice.
source to share