首页 > 解决方案 > 如何使用我的使用量和量对成本的括号动态计算水费成本?

问题描述

我正在尝试使用连接到我的干线的流量计来预测我的水费。

我的账单使用的价格为: 27.54kL @ $2.392 91.80kL @ $3.413 300.00kL @ $3.699

例如,如果我使用 250kL,我的账单将被分解为:

1st rate: There are more than 27.54kL in 250kL, so cost of this rate is: 27.54*$2.392 = $65.88 (250 - 27.54 = 222.46kL remaining for the next rate)
2nd rate: There are more than 91.80kL in 222.46kL, so cost of this rate is = 91.80*$3.413 = $313.31 (222.46 - 91.80 = 130.66kL remaining for next rate)
3rd rate: There are less than 300kL in 130.66kL, but more than 0, so cost of this rate is: 130.66*$3.699 = $483.31 (130.66 - 130.66 = 0L remaining for next rate (if there was a 4th))

Total = sum of all rate costs = $862.50

我怎样才能以动态的方式计算它,以便如果费率甚至费率的数量发生变化,它仍然有效?我可以轻松地重现上述内容,但我想使用列表和列表理解或其他循环来产生最终成本。

这将计算我需要什么,但它不是动态的:

volumeCostDict = [[27.54,2.392], [91.80,3.413], [350.00,3.699]]
volume = 271 # kilolitres

rate1Volume = volumeCostDict[0][0] if volume > volumeCostDict[0][0] else volume
rate1Cost = rate1Volume * volumeCostDict[0][1]

rate2Volume = volumeCostDict[1][0] if volume > (volumeCostDict[0][0] + volumeCostDict[1][0]) else volume - volumeCostDict[0][0]
rate2Cost = rate2Volume * volumeCostDict[1][1]

rate3Volume = volumeCostDict[2][0] if volume > (volumeCostDict[0][0] + volumeCostDict[1][0] + volumeCostDict[2][0]) else volume - volumeCostDict[0][0] - volumeCostDict[1][0]
rate3Cost = rate3Volume * volumeCostDict[2][1]

print(rate1Cost)
print(rate2Cost)
print(rate3Cost)

totalCost = rate1Cost + rate2Cost + rate3Cost

谢谢!

标签: python-3.x

解决方案


我明白了,只需要先对其进行静态编码,然后制定模式以动态应用它。可能还有一种更简单的方法,但这有效 编辑:适用于所有情况

volumeCostDict = [[27.54,2.392], [91.80,3.413], [350.00,3.699]]
volume = 271 # kilolitres

rateVolumes = [volume_kL \
                 if volume_kL < volumeCostDict[i][0] and i == 0 \
                 else volumeCostDict[i][0] \
                 if volume_kL > sum([volumeCostDict[j][0] for j in range(i+1)]) \
                 else volume_kL - sum([volumeCostDict[k][0] for k in range(i)]) \
                 if (volume_kL - sum([volumeCostDict[k][0] for k in range(i)])) > 0 \
                 else 0 \
                 for i in range(len(volumeCostDict))]
totalCost = sum([rateVolumes[i]*volumeCostDict[i][1] for i in range(len(rateVolumes))])
print(rateVolumes)
print(totalCost)

推荐阅读