python - How to check if a number is in a interval -
suppose got:
first_var = 1 second_var = 5 interval = 2
i want interval second_var second_var ± interval
(from 3 7). wank check if first_var in interval. in specific case want false
if first_var = 4
, want true
i can this:
if (first_var > second_var-interval) , (first_var < second_var+interval): #true
is there more pythonic way this?
i use class __contains__
represent 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 define function interval
simplify syntax:
def interval(middle, deviation): return interval(middle, deviation)
then can call follows:
>>> 8 in interval(middle=6, deviation=2) true >>> 8 in interval(middle=6, deviation=1) false
with python 2 solution more efficient using range
or xrange
don't implement __contains__
, have search matching value.
python 3 smarter , range
generating object efficient xrange
, implements __contains__
doesn't have search valid value. xrange
doesn't exist in python 3.
this solution works floats.
also, note, if use range
need careful of off-by-1 errors. better encapsulate it, if you're going doing more once or twice.
Comments
Post a Comment