dimanche 24 janvier 2021

Best way to simplify multiple conditional statements

I have a single action to perform depending on the values of a,b,c,d but I may not get all the 4 values every time there will be 16 possible permutations I can get ϕ ,{a},{b},{c},{d},{a,b},{a,c},{a,d},{b,c},{b,d},{c,d},{a,b,c},{a,b,d},{a,c,d},{b,c,d},{a,b,c,d}.

def call_me (a=None,b=None,c=None,d=None):
    if a:
        a1 = a+1
    if b:
        b1 = b+2
    if c:
        c1 = c+3
    if d:
        d1 = d+4
    if (a<a1) and (b<b1) and (c<c1) and (d<d1):
        #Do something 
        return "something"

If I call call_me(a = 1,b = 2,c = 3,d =4) the program will work but in case If I do call_me(a = 1,b = 2,c = 3) it will throw me an error UnboundLocalError: local variable 'd1' referenced before assignment

So the only way I can think is to cover all the combinations (2 ^ N)

if a and b and c and d:
    if (a<a1) and (b<b1) and (c<c1) and (d<d1):
        return "something 1"

if a and b and c:
    if (a<a1) and (b<b1) and (c<c1):
        return "something 2"

if a and b and d:
    if (a<a1) and (b<b1) and (d<d1):
        return "something 3"
#and so on... 

Is there any way to simplify this by not using so many if statements?

Aucun commentaire:

Enregistrer un commentaire