Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if a certain number is within a list of ranges

Tags:

python

list

range

How do I test how many times a certain number is outside my list of ranges?

Example:

value = 1
Ranges_array = [[0, 2], [2, 4], [0, 3]]
output = 1

So, the output generated will be 1 because there is only one range where the value of 1 does not lie within.

like image 591
damien Avatar asked Oct 25 '17 16:10

damien


People also ask

How do you check if number is within a range?

If x is in range, then it must be greater than or equal to low, i.e., (x-low) >= 0. And must be smaller than or equal to high i.e., (high – x) <= 0. So if result of the multiplication is less than or equal to 0, then x is in range.

How do you check if a range of numbers is in a list Python?

To check if given number is in a range, use Python if statement with in keyword as shown below. number in range() expression returns a boolean value: True if number is present in the range(), False if number is not present in the range. You can also check the other way around using not to the existing syntax.


2 Answers

Well, those aren't actually Ranges, but two-element lists. You could use manual comparison, as in the other answers, but in my answer I turn them into actual Range objects.

Since Python's range(a,b) constructor is inclusive at a (that is, a is inside the range) and exclusive at b (b is outside the range), you have to add 1 to one of the endpoints if you want them both to be inclusive or exclusive. I assumed you wanted inclusive, so added 1 to the high end point:

sum(1 for a,b in Ranges_array if value not in range(a,b+1))
like image 115
Mark Reed Avatar answered Nov 14 '22 22:11

Mark Reed


You could use sum and a generator expression:

>>> sum(not a <= value <= b for a, b in ranges_array)
1

a and b are lower and upper range bounds, respectively. a <= value <= b is a chained comparison, equivalent to a <= value and value <= b. The final return value is the number of times the not a <= value <= b expression evaluated to True.

We can get a slightly longer but more readable solution if we apply De Morgan's laws:

>>> sum(value < a or value > b for a, b in ranges_array)
1

Technically, you can use range as shown in other answers, but they will be slower in Python 3 (due to the creation of the range object) and much slower in Python 2 (because Python 2's range creates an actual list, and containment checks on lists are O(n)):

$ python3.6 -m timeit -s "a, b, value = 0, 1000, 500" "a <= value <= b"
10000000 loops, best of 3: 0.0343 usec per loop
$ python3.6 -m timeit -s "a, b, value = 0, 1000, 500" "value in range(a, b + 1)"
1000000 loops, best of 3: 0.28 usec per loop
$ python2.7 -m timeit -s "a, b, value = 0, 1000, 500" "value in range(a, b + 1)"
100000 loops, best of 3: 7.97 usec per loop
like image 42
vaultah Avatar answered Nov 15 '22 00:11

vaultah