简体   繁体   中英

How to reduce amount of if conditions on Python?

I have a function in Python which looks like this:

def ldm_discount(ldm):
  if ldm <= 1:
    return 0.3
  if ldm <=2:
    return 0.38
  if ldm <=3:
    return 0.45
  if ldm <=4:
    return 0.51
  if ldm <=5:
    return 0.57
  if ldm <=6:
    return 0.63
  if ldm <=7:
    return 0.69
  if ldm <=8:
    return 0.75
  if ldm <=9:
    return 0.80
  if ldm <=10:
    return 0.85
  else:
    return 1

It seems to me there might be a better way. How can I reduce the amount of if statements?

UPDATE: Btw I can't use imports

Assign all outputs in a list, iterate over a list and match ldm with list indices.

vals = [0.3,0.38,0.45,0.51,0.57,0.63,0.69,0.75,0.80,0.85]
def ldm_discount(ldm):
    for i in range(1,len(vals)+1):
        if ldm <= i:
            return vals[i-1]
    return 1
ldm_discount(2)
>> 0.38
ldm_discount(5)
>> 0.57
def ldm_discount(ldm):
    ldm = round(ldm)
    ldm_discount={1:0.3,2:0.38}
    discount = ldm_discount.get(ldm,None)
    return discount
from math import ceil def ldm_discount(ldm): index = ceil(ldm) values = [0.3, 0.38, 0.45, .......] if ldm <= 10: return values[index - 1] else: return 1

You can have a single if statement by finding out the correct index directly:

import math
def ldm_discount(ldm):
    discounts = [0.3, 0.38, 0.45, 0.51, 0.57, 0.63, 0.69, 0.75, 0.8, 0.85]
    return discounts[math.ceil(ldm) - 1] if ldm <= 10 else 1

Notice that you must make sure ldm is not negative or zero, otherwise it will do a negative indexing or an IndexError (out of range).

Or you can slightly change the condition:

import math
def ldm_discount(ldm):
    discounts = [0.3, 0.38, 0.45, 0.51, 0.57, 0.63, 0.69, 0.75, 0.8, 0.85]
    return discounts[math.ceil(ldm) - 1] if 0 < ldm <= 10 else 0 if ldm == 0 else 1

Edit (no imports)

math is part of the built-in python modules, but in case you can't use any kind of import, you can do your own ceil .

discounts = [0.3, 0.38, 0.45, 0.51, 0.57, 0.63, 0.69, 0.75, 0.8, 0.85]
def ldm_discount(ldm): 
    casted = int(ldm)
    return discounts[casted - 1 if ldm == casted else casted] if 0 < ldm <= len(discounts) else 0 if ldm == 0 else 1

Python 3.10 introduces the "match" statement, which in other languages is usually known as a "switch" statement. See PEP 622

That said, as you mentioned, there's probably a nicer way to do what you're currently doing.

You could for example use a dictionary and loop through it:

values = {
 1: 0.3,
 2: 0.38,
 ...
}

for threshold in values.keys():
 if ldm <= threshold:
  return values

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