Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

python - 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?

question from:https://stackoverflow.com/questions/65870180/best-way-to-simplify-multiple-conditional-statements

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can check for existence inside of each conditional where you're using the value:

if (a is None or a<a1) and (b is None or b<b1) and (c is None or c<c1) and (d is None or d<d1):
    # Do something

This way if any of the passed values is still None, that parenthesized expression will become True and won't interfere with the rest of the checks.


Another way to do it is to check the condition related to each variable at the same time as you check for existence, and just early-exit if it fails:

if a:
    a1 = a+1
    if not a<a1:
        return
if b:
    # etc.

# All conditions passed, do something. 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...