Suppose I got:
first_var = 1
second_var = 5
interval = 2
I want an interval from second_var like second_var ± interval
(from 3 to 7).
I wank to check if first_var is in that interval.
So in this specific case I want False
If first_var = 4
, I want True
I can do this:
if (first_var > second_var-interval) and (first_var < second_var+interval):
#True
Is there a more pythonic way to do this?
You can use math-like sequence as Python supports that
if (second_var-interval < first_var < second_var+interval):
# True
Note that comments in python begin with a #
I use a class with __contains__
to represent the 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 as follows:
>>> 8 in interval(middle=6, deviation=2)
True
>>> 8 in interval(middle=6, deviation=1)
False
With Python 2 this solution is more efficient than using range
or xrange
as they don't implement __contains__
and they have to search for a matching value.
Python 3 is smarter and range
is a generating object which is efficient like xrange
, but also implements __contains__
so it doesn't have to search for a valid value. xrange
doesn't exist in Python 3.
This solution also works with floats.
Also, note, if you use range
you need to be careful of off-by-1 errors. Better to encapsulate it, if you're going to be doing it more than once or twice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With