I know that I can hash singular values as keys in a dict
. For example, I can hash 5
as one of the keys in a dict
.
I am currently facing a problem that requires me to hash a range of values.
Basically, I need a faster way to to do this:
if 0 <= x <= 0.1:
# f(A)
elif 0.1 <= x <= 0.2:
# f(B)
elif 0.2 <= x <= 0.3:
# f(C)
elif 0.3 <= x <= 0.4:
# f(D)
elif 0.4 <= x <= 0.5:
# f(E)
elif 0.5 <= x <= 0.6:
# f(F)
where x
is some float
parameter of arbitrary precision.
The fastest way I can think of is hashing, but here's the problem: I can use (0.1, 0.2)
as a key, but that still is going to cost me O(n) runtime and is ultimately no better than the slew of elif
s (I would have to iterate over the keys and check to see if key[0] <= x <= key[1]
).
Is there a way to hash a range of values so that I can check the hash table for0.15
and still get #execute B
?
If such a hashing isn't possible, how else might I be able to improve the runtime of this? I am working with large enough data sets that linear runtime is not fast enough.
EDIT: In response to cheeken's answer, I must note that the intervals cannot be assumed to be regular. As a matter of fact, I can almost guarantee that they are not
In response to requests in comments, I should mention that I am doing this in an attempt to implement fitness-based selection in a genetic algorithm. The algorithm itself is for homework, but the specific implementation is only to improve the runtime for generating experimental data.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…