vendredi 24 mars 2017

Removing Multiple Ifs in with inequality conditions

I am trying to convert this code into less bulky format, I know we can remove ifs by using dictionary but that goes only when you have equality, If you are looking for some range check, what should be the alternative. My code is as follows:

def dispersion(x):
   v = float(x) / 100
   if v <= -.20:
     return '< -20%'
   elif -.20 < v <= -.10:
     return '-20% to -10%'
   elif -.10 < v <= -0.05:
     return '-10% to -5%'
   elif -.05 < v <= .0:
     return '-5% to 0%'
   elif 0 < v <= .05:
     return '0% to 5%'
   elif .05 < v <= .10:
     return '5% to 10%'
   elif .10 < v <= .20:
     return '10% to 20%'
   else:
     return '> 20%'

P.S- I was thinking of using binary search , but not able to formulate into the code.

Aucun commentaire:

Enregistrer un commentaire