What is the fastest way to check if a number is in specific range in python?
Question: I have 5 ranges:

    
    
    1-50 ---> "range1"
    51-100 ---> "range2"
    101-150 ---> "range3"
    151-200 ---> "range4"
    201-250 ---> "range5"
    

Ranges do not overlap, each range has lower and upper bound, next range starts
where the previous one ends. I decide the range lengths. they might not be
equal in size.

I have a variable that shows a number, for example

    
    
    x = 153
    

If x is between 1 and 50 then it should return "range1", if between 51 and 100
then "range2", and so on. What is the fastest way of doing it in python,
considering there may be much more than 5 ranges, and the number is large?


Answer: Because your ranges are strictly adjacent and in increasing order, you can use
bisection:

    
    
    from bisect import bisect
    
    ranges = [1, 51, 101, 151, 201]
    if 0 < x <= 250:
        print('range{}'.format(bisect(ranges, x))
    else:
        print('Out of bounds')
    

Bisection takes O(logN) steps to find the matching range out of N
possibilities.

