简体   繁体   中英

Does anyone know how to factor out a repeated if/else structure?

I have code that is in the form

if scenarioOne:
    actionC
elif scenarioTwo:
    if B:
         actionB
    else:
         actionC
else:
    if A:
         actionA
    elif B:
         actionB
    else:
         actionC

There's code duplication but im not sure how to factor it out. One option is a list of (predicate,lambda) pairs then I could iterate over the list to find the first predicate that evaluates to true and execute the corresponding action. I would pair actionC with an always true predicate. Not sure if theres a better way, either in Python or functional languages in general.

Well, maybe it is not the most illustrative case but I'll put it here as an example. Karnaugh maps are a powerful tool to simplify binary functions and can be applied in many situations similar to this.

TLDR:

# for brewity, s1 = scenarioOne and s2=scenarioTwo
if (A and not s1 and not s2):
    actionA
elif (B and not s1 and (not A or s2)):
    actionB
else:
    actionC

Here are the truth tables. Rows are AB values, columns are scenarioOne (s1) + scenarioTwo (s2)

actionA
    00  01  11  10
00  
01
11   1
10   1


actionB
    00  01  11  10
00  
01   1   1
11       1
10   

actionC
    00  01  11  10
00   1   1   1   1
01           1   1
11           1   1
10       1   1   1

First, three actions are exclusive and fully cover the input space. Now, the first table: two 1s are together and can be expressed as:

A = !s1 !s2 A

Second table: two pairs,

B = !s1 s2 B | !s1 !A B = !s1 B (!A | s2)

The rest is C, but if we want formula it is three elements: right half, top row, and pair in the middle of the bottom row:

C = s1 | !A !B | A !B s2 = s1 | !B (s2 | !A)

Try something like this :)

if scenarioOne:
    actionC
elif (A && !scenarioTwo):
    actionA
else:
    if B:
         actionB
    else:
         actionC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM