[Tutor] Setting thresholds in a compact way
Richard Damon
Richard at Damon-Family.org
Wed Jan 1 14:18:53 EST 2020
On 1/1/20 11:20 AM, Robert Alexander wrote:
> Dear friends,
> First of all let me wish a great 2020 for all of you kind souls and seekers
> of knowledge :)
>
> I am trying to setup a varying time.sleep value (in house) depending on a
> priorly determined threshold.
>
> If threshold <= .9 AND > .8 then sleep should be 6 hours
> if threshold <= 0.8 AND > .4 then sleep should be 4 hours
> if threshold <= .4 AND > .1 then sleep should be 3 hours
> if threshold <= .1 then sleep should be set to 1 hour
>
> Instead of a complex/lengthy series of (nested?) if/ands based on the
> above, I was wondering if I could declare a dictionary such as:
>
> sleep_thresholds_hours = {.9:6, .8:4, .4:3, .1:1}
>
> And then use some sort of single statement to set the sleep_time to the the
> proper value.
>
> Not even quite sure that using floats (albeit single decimal) as dictionary
> keys will be ok.
>
> Getting old and in 2020 even older and my brain fogged by too much food :)
>
> Thanks in advance
The straight forward way to state that (since you ranges are all
consecutive) would be
if threshold <= 0.1: sleep(1 hour)
elif threshold <= 0.4: sleep (3 hour)
elif threshold <= 0.8: sleep(4 hours)
elif threshold <= 0.9: sleep(6 hours)
else: # what you want to do otherwise.
You can also simplify your if statements (and get the right syntax with
if 0.8 < threshold <= 0.9: sleep 6 hours
if 0.4 < threshold <= 0.8: sleep 4 hours
if 0.1 < threshold <= 0.4: sleep 3 hours
if threshold <= 0.1: sleep 1 hour
The dictionary is an interesting idea, but I don't know of a built in
way do the sort of lookup you are suggesting. Dictionaries are designed
to optimize looking up exact values quickly, not find the next value.
--
Richard Damon
More information about the Tutor
mailing list