Naramsim
Naramsim

Reputation: 8732

How to check if a number is in a interval

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?

Upvotes: 7

Views: 14619

Answers (4)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

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.

Upvotes: 6

Drumnbass
Drumnbass

Reputation: 914

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

Upvotes: 0

user734094
user734094

Reputation:

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 bit long!

Upvotes: 1

Bhargav Rao
Bhargav Rao

Reputation: 52071

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 #

Upvotes: 15

Related Questions