If you have an easy way to calculate a range from a point, for example, if all ranges are of a fixed size, you can use:
def getIndex(p): start = floor(p/100)*100 return (start, start+100)
Then define a dict:
r = {(0, 100): 'foo', (100, 200): 'bar'}
and access:
r[getIndex(42)]
This method is effective as:
- You do not have an element in the dict for each number in the range (this also allows you to have valid "keys" values)
- you're not going to, although the whole dict is to find the value, getting the value of O (1)
In addition, your getIndex function can be more complex, for example, if your ranges are irregular in length, your getIndex function can binary search for a sorted list of range boundaries and return a range tuple, not more than O(1) but O(log(n)) not bad ...
source share