Search code examples
pythonif-statementboolean-expression

Is there a faster way of evaluating every combination of booleans in an if statement in python?


If I have 4 booleans e.g

if ((a(x) == True) and (b(x) == True) and (c(x) == True) and (d(x) == True)

then I want to do something different for each combination including when only 3 of them are true (including which ones), 2..., then only each 1... etc...

Is there a quicker way than writing a bunch of elifs?

Possibly using a loop


Solution

  • The solution with the lookup table is great but if you wanted to do something that takes less memory and around the same speed. You can use the if statement results to build on each other this way you'd only have 2^4(16) cases i.e:

    if (a(x)):
        if(b(x):
            if(c(x)):
                if(d(x)):
                    #do x
                else:
                    #do y
            else:
                if (d(x)):
                    #do z
                else:
                    #do w
             #...