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?

+3


source to share


4 answers


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.

+3


source


You can use mathematical sequence as Python supports

if (second_var-interval < first_var < second_var+interval):
     # True

      



Note that comments in python start with #

+7


source


You can use lambdas:

lmd = lambda fv, sv, inval: print('True') if \
    sv - inval < fv < sv + inval else print('False')

      

and use it like:

lmd(first_var, second_var, interval)

      

but it's a little longer!

+1


source


if (first_var in range(second_var-interval, second_var+interval+1)):
    #Do something

      

0


source







All Articles