范围和一些常数之间的双射关系?

时间:2011-01-25 16:20:14

标签: python set bijection

请将此问题移至Code Review -area。它更适合那里,因为我知道下面的代码是垃圾,我想要批评反馈来完成重写。

如何在Python中编写set-to-constants关系?因此,如果范围内为A,则返回其对应的常量。

[0,10]    <-> a
]10,77]   <-> b
]77,\inf[ <-> c

嗅觉代码,不好。

    # Bad style

    provSum=0


    # TRIAL 1: messy if-clauses
    for sold in getSelling():
            if (sold >=0 & sold <7700):
                    rate =0.1 
            else if (sold>=7700 & sold <7700):   
            #won't even correct mistakes here because it shows how not to do things
                    rate =0.15
            else if (sold>=7700):
                    rate =0.20


    # TRIAL 2: messy, broke it because it is getting too hard to 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

2 个答案:

答案 0 :(得分:3)

如果列表长于三个条目,我会使用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 is negative

但是这只有三个值似乎有点过分了......

编辑:第二个想法,最可读的变体可能是

if sold >= 7700:
    rate = 0.2
elif sold >= 2000:
    rate = 0.15
elif sold >= 0:
    rate = 0.1
else:
    # sold is negative

答案 1 :(得分:1)

if (sold >=0 & sold <7700):

相当于

if 0 <= sold < 7700:

我不知道非常好的方式来映射范围,但这使它看起来更好看。

您也可以使用第二种方法:

provisions = {(0, 2000) : 0.1, (2000,7700):0.15, (7700, float("inf")):0.20}

# loop though the items and find the first that's in range
for (lower, upper), rate in provisions.iteritems():
    if lower <= sold < upper:
        break # `rate` remains set after the loop ..

# which pretty similar (see comments) to
rate = next(rate for (lower, upper), rate in 
                 provisions.iteritems() if lower <= sold < upper)