In Python, how can I map from a range of values to one concrete value?
Basically, I want a dictionary, which I can fill with ranges and index with numbers:
rd = rangedict()
rd[(0, 10)] = 5
print rd[4] # prints 5
print rd[6] # prints 5
rd[(5, 15)] = 20
print rd[4] # prints 5
print rd[6] # prints 20
You could use an interval tree
pip install intervaltree
from intervaltree import Interval, IntervalTree
rd = IntervalTree()
rd[0:10] = 5
print rd[4]
print rd[5]
https://pypi.python.org/pypi/intervaltree
Thanks to the comments I could find a solution using the intervaltree
package.
from intervaltree import IntervalTree
tree = IntervalTree()
tree.addi(0, 10, 5)
print tree[4]
print tree[6]
# need to chop before, as the library stores both intervals otherwise
tree.chop(5, 15)
tree.addi(5, 15, 20)
print tree[4]
print tree[6]