Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 526
Naramsim Avatar asked May 15 '15 08:05

Naramsim


2 Answers

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 #

like image 50
Bhargav Rao Avatar answered Sep 27 '22 21:09

Bhargav Rao


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.

like image 27
Peter Wood Avatar answered Sep 27 '22 20:09

Peter Wood