python - Bijective relations between ranges and some constants? -
please, move question code review -area. better suited there because know code below junk , wanted critical feedback complete rewrite.
how can write set-to-constants relations in python? if a
in range, return corresponding constant.
[0,10] <-> ]10,77] <-> b ]77,\inf[ <-> c
smelling code, bad.
# bad style provsum=0 # trial 1: messy if-clauses sold in getselling(): if (sold >=0 & sold <7700): rate =0.1 else if (sold>=7700 & sold <7700): #won't correct mistakes here because shows how not things rate =0.15 else if (sold>=7700): rate =0.20 # trial 2: messy, broke because getting hard read provisions= {"0|2000":0.1, "2000|7700":0.15, "7700|99999999999999":0.20} if int(sold) >= int(border.split("|")[0]) & int(sold) < int(border.split("|")[1]): print sold, rate provsum = provsum + sold*rate
if list longer mere 3 entries, use bisect.bisect()
:
limits = [0, 2000, 7700] rates = [0.1, 0.15, 0.2] index = bisect.bisect(limits, sold) - 1 if index >= 0: rate = rates[index] else: # sold negative
but seems bit overengineered 3 values...
edit: on second thought, readable variant is
if sold >= 7700: rate = 0.2 elif sold >= 2000: rate = 0.15 elif sold >= 0: rate = 0.1 else: # sold negative
Comments
Post a Comment