Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write If statements for all 2^N boolean conditions (python)

I have a function which needs to execute a query based on the query instances inputted.. but as the conditions are increasing it is becoming tedious for me to list all of them. For example: suppose i have two conditions initially:

if (cond_1 == True and cond_2 == False):
    do something
elif  cond_1 == True and cond_2 == True:
    do something else
elif cond_1 == False and cond_2 == True:
    do this

....

so I guess if conditions takes on binary values then there are 2^n statements i have to write :(

so now i have 3 condition variables (8 statements).. and i am afraid that this number might increase in future. Is tehre a better way to check these conditions??

like image 513
frazman Avatar asked Mar 01 '12 23:03

frazman


1 Answers

Do you need to always write all all 2^n possibilities?

And are all things you have to do different (so also 2^n actions?)

However I can give some hints:

Don't use '== True' or '== False'

What you wrote equals:

if cond_1 and not cond_2:
    do something 
elif cond_1 and cond_2:
    do something else 
elif not cond_1 and cond_2:
    do this 

Also think about writing:

if cond_1:
    if cond_2:
        Do something
    else:
        Do something 
else:
    if cond_2:
        Do something
    else:
        Do something 

You also can define functions depending on the values:

def __init__(self):
    self.actions = {
      (False, False): action_1,
      (False, True ): action_2,
      ...
    }

def action_1(self):
    some action

def action_2(self):
    some action

....

and call it with:

self.actions[(cond_1, cond_2)]()

If you want to optimize the number of options in case you have different conditions with similar actions, take a look to Karnaugh Maps (it is easier than it looks like):

http://en.wikipedia.org/wiki/Karnaugh_map

like image 75
Michel Keijzers Avatar answered Nov 14 '22 22:11

Michel Keijzers