Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - switch alternative for non-discrete comparisons

Maybe this question has been asked before, but I couldn't find it. I am trying to implement something that determines what range a given value is in. In this example, x may be any real number.

def f(x):
    if x < 0.1:
        do_something_1()
    elif 0.1 <= x < 1:
        do_something_2()
    elif 1 <= x < 10:
        do_something_3()
    elif x >= 10:
        do_something_4()

...you get the idea.

I've seen plenty of examples of dictionaries replacing switch statements in Python, but I've always understood dictionaries as indexing discrete values.

I find it hard to believe that the if-elif-else chain is the best solution in this situation. Does anyone know of a better one?

like image 407
Benjamin Hodgson Avatar asked May 27 '26 14:05

Benjamin Hodgson


1 Answers

An easy way to improve this is not to repeat the lower bounds. Your code is equivalent to

if x < 0.1:
    do_something_1()
elif x < 1:
    do_something_2()
elif x < 10:
    do_something_3()
else:
    do_something_4()

If there are really many values, you might want to bisect instead, but with only four options, the above code is probably the best solutuion, at least in terms of readability and speed.

like image 153
Sven Marnach Avatar answered May 30 '26 08:05

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!