How to compute a percentage increase/decrease multiplier in python without if statements

后端 未结 3 1778
渐次进展
渐次进展 2021-01-27 16:34

I have a scenario in which the user enter a positive, 0, or negative value which represents a percentage increase, no change, or percentage decrease, respectively. Example: 2.5

相关标签:
3条回答
  • 2021-01-27 17:08

    if and else can actually be used in expressions on one line: x = a if b else c. You can't use elif, though, so you'll have to first refactor your code so it doesn't use them:

    if U == 0:
       multiplier = 1
    else:
        if U > 0:
           multiplier = U/100.0 + 1
        else:
           multiplier = (100 - (U * -1.0))/100.0
    

    This reduces to

    if U == 0:
       multiplier = 1
    else:
       multiplier = U/100.0 + 1 if U > 0 else (100 - (U * -1.0))/100.0
    

    Which reduces to

    multiplier = 1 if U == 0 else (U/100.0 + 1 if U > 0 else (100 - (U * -1.0))/100.0)
    
    0 讨论(0)
  • 2021-01-27 17:14

    You just need to use the distributive property of division:

    multiplier = 1 + U/100.0

    This is actually what your code does. You just separated three branches of a if that did exactly the same. Let's do some easy math step-by-step from your original code:


    if U == 0:
       multiplier = 1
    elif U > 0:
       multiplier = U/100.0 + 1
    else:
       multiplier = (100 - (U * -1.0))/100.0
    

    if U == 0:
       multiplier = 1 + 0                 #sum 0 for convenience
    elif U > 0:
       multiplier = 1 + U/100.0           #swap order of addition
    else:
       multiplier = (100 + U)) / 100.0    #multiplying by -1 is just changing the sign
    

    if U == 0:
       multiplier = 1 + U/100.0    # since U is 0 in this branch, U/100.0 == 0
    elif U > 0:
       multiplier = 1 + U/100.0
    else:
       multiplier = 1 + U/100.0    # distributive property of division
    

    Since the executed code is the same for the three branches, there's no point having a if:

    multiplier = 1 + U/100.0
    
    0 讨论(0)
  • 2021-01-27 17:17

    Kevin's answer is technically completely correct, but your code can be simplified a whole lot just from a math standpoint.

    You don't need to be performing if-then-else checks on this mathematical operation. Consider the input of "-3": In your code, this will go into the third block, evaluate as (100 - (-3 * -1.0)) / 100.0 = (100 - 3.0) / 100.0 = 0.97.

    This is equivalent to the value U going into the second block, evaluated as (-3 / 100.0) + 1 = -0.03 + 1 = 0.97.

    Now consider the input of 0: No matter which block it goes in to, the "multiplier" value will come out as 1.

    So just have your code be:

    multiplier = 1 + (U / 100.0)
    

    and you'll be set.

    0 讨论(0)
提交回复
热议问题