Question

I am trying to check each index in an 8 digit binary string. If it is '0' then it is 'OFF' otherwise its 'ON'.

Is there a more concise way to write this code with a switch-like feature.?

Was it helpful?

Solution

No it doesn't. When it comes to the language itself, one of the core Python principles is to only have one way to do something. The switch is redundant to:

if x == 1:
    pass
elif x == 5:
    pass
elif x == 10:
    pass

(without the fall-through, of course).

The switch was originally introduced as a compiler optimization for C. Modern compilers no longer need these hints to optimize this sort of logic statement.

OTHER TIPS

Try this instead:

def on_function(*args, **kwargs):
    # do something

def off_function(*args, **kwargs):
    # do something

function_dict = { '0' : off_function, '1' : on_function }

for ch in binary_string:
   function_dict[ch]()

Or you could use a list comprehension or generator expression if your functions return values:

result_list = [function_dict[ch]() for ch in binary_string]

else-if is bad practice, since they are unsafe when they get too long, and involve unnecessary conditional branching (maybe affecting compiler / caching).

try this...

class Functions():
    @staticmethod
    def func():
        print("so - foo")
    @staticmethod
    def funcWithArgs( junk ):
        print(junk, "foo")

# fill in your cases here...
cases = {
    "a" : Functions.func ,
    "b" : Functions.funcWithArgs ,
    "c" : Functions.funcWithArgs
}

def switch( ch, cases, *args ):
    try:
        len(*args)  # empty args
    except TypeError:
        return cases[ ch ]( )
    return cases[ ch ]( *args )

# try out your switch...
switch("a", cases)  # "so - foo"
switch("b", cases, "b -")  # "b - foo"
switch("c", cases, "c -")  # "c - foo"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top