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

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

提交回复
热议问题