I have a list of many Python objects like this:
class RangeClass(object):
def __init__(self,address,size):
self.address=address
self.size=size
#other attributes and methods...
Then, I have a list (rangelist) of RangeClass objects.
I need to find within which range a given value is.
I can use some code like this:
for r in ragelist:
if(value>=r.address and value<(r.address+r.size)):
return r
return None
But I think there is a faster way. Ranges have arbitrary size, but we can assume that they don’t overlap.
Thank you.
If you have many values to test, then you could use the bisect module to find which range the values are in more quickly.
If
m= the number of values to test, andn=len(rangelist)then looping through the values and rangelist as you suggest would take
O(m*n)time.If you use bisection, then you must first sort the starting addresses
O(nlogn)and find each value’s place in rangelistO(m*logn).So if
then bisection wins. For large
n,O(m*logn)is miniscule compared toO(m*n).So the inequality above would be true if
or equivalently, when
for some constant C.
Thus, when
nis large andC log(n) < m, you might try something like