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??
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With