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

后端 未结 3 1785
渐次进展
渐次进展 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: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
    

提交回复
热议问题