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.
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.
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.
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))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With