Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
         #...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading