P. A. P. A. - 1 month ago 13
Python Question

multiple conditionals effciently

How can I execute the following code in a more efficient way in python? The input flags are binary valued. The output depends on all possible permutations of the flag.

def f1():

return 1

def f2():

return 2

def f3():

return 3


def g(p1, p2, p3):

if p1 == 1 & p2 == 0 & p3 == 0:
f1()

elif: p1 == 0 & p2 == 1 & p3 == 0:
f2()

elif: p1 == 0 & p2 == 0 & p3 == 1:
f3()

elif: p1 == 1 & p2 == 1 & p3 == 1:
f1()
f2()


and so on.

Answer

If you want to use the arguments (p1, p2, p3) as flags, you could always pack those arguments as a list using *args (see this, this and this) and put your functions in a list (yep, Python lets you do that) and get something like:

def f1():
    return 1

def f2():
    return 2

def f3():
    return 3 

def g(*ps):
    functions = [f1, f2, f3]
    for i, p in enumerate(ps):
        if p == 1:  # Could do just `if p:` (0 evaluates to False, anything else to True)
            print(functions[i])()  # Notice the () to actually call the function 

if __name__ == "__main__":
    print("Run 1 0 0")
    g(1, 0, 0)
    print("Run 1 1 0")
    g(1, 1, 0)
    print("Run 0 1 0")
    g(0, 1, 0)
    print("Run 1 1 1")
    g(1, 1, 1)