Testing if a specific number is in the range list

How to check how many times a certain number is outside my range list?

Example:

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

Thus, the result will be equal to 1, because there is only one range where the value of 1 does not lie inside.

+5
source share
6 answers

Well, actually these are not ranges, but two-element lists. You can use manual comparison, as in other answers, but in my answer I turn them into actual Range objects.

Since the Python constructor range(a,b) included in a (i.e., a is inside the range), and the exception in b ( b is outside the range), you need to add 1 to one endpoints if you want to they were inclusive or exclusive. I suggested that you want to include by adding 1 to the top point:

 sum(1 for a,b in Ranges_array if value not in range(a,b+1)) 
+4
source

You can use sum and generator expression:

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

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

We can get a slightly longer, but more readable solution if we apply the laws of De Morgan:

 >>> 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 (since Python 2 range creates the actual list and list containment checks 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 
+2
source

an understanding of the list should be enough.

 output=len([k for k in Ranges_array if k[0]>value or k[1]<value]) 
0
source

Using list comprehension :

 >>> sum([1 for x,y in ranges if not x<=value<=y]) => 1 #OR >>> len([1 for x,y in ranges if not x<=value<=y]) => 1 

Using generators (recommended as it will be faster):

 >>> sum(1 for x,y in ranges if not x<=value<=y) => 1 

#driver:

 IN : ranges = [[0,2], [2,4], [0,3]] 
0
source

You can try:

 value = 1 Ranges_array= [[0,2], [2,4], [0,3]] output = 0 for r in Ranges_array: if value not in range(r[0], r[1]): output +=1 
0
source

Just a parellel solution:

 my_value = 1 Ranges_array = [[0,2],[2,4],[0,3]] output = 1 count = 0 for listt in Ranges_array: if not my_value in range(listt[0],listt[-1]): count+= 1 print count 
0
source

Source: https://habr.com/ru/post/1272891/


All Articles