公司的面试题,已知每日用电量,求分段计费模式下计算每日的电费,当初做的时候遇到一个小坑,没考虑单日用电量跨越两个以上计费区间这种情况,
现在把这道题用新学的python实现出来并测试通过,算是功德圆满吧。
1 # coding:utf-8
2 import sys
3
4 MAX_INT = sys.maxsize
5 pricelist = []
6 priceIdx = 0
7
8
9 # 价格区间对象
10 class PriceRange(object):
11 def __init__(self, price, min, max=MAX_INT):
12 self.price = price
13 self.min = min
14 self.max = max
15
16
17 # 计算单日花费
18 def getOnedayCost(pre, total):
19 global priceIdx
20 if priceIdx == len(pricelist):
21 priceIdx = priceIdx - 1
22 price = pricelist[priceIdx].price
23 max = pricelist[priceIdx].max
24
25 if total > max:
26 part1 = (max - pre) * price
27 pre = max
28 priceIdx = priceIdx + 1
29 if priceIdx == len(pricelist):
30 return part1 + (total - max) * price
31 else:
32 return part1 + getOnedayCost(pre, total)
33 else:
34 return (total - pre) * price
35
36
37 # 计算总花费
38 def caculate(usedlist):
39 total = 0
40 cost = []
41 for used in usedlist:
42 pre = total
43 total = used + total
44 cost.append(getOnedayCost(pre, total))
45 return cost
46
47
48 # 校验价格区间
49 def verifyPriceBrand():
50 if pricelist is None or len(pricelist) == 0:
51 raise Exception("the price range can not be null!")
52 tmp = pricelist[0].max
53 for idx in range(1, len(pricelist)):
54 if not pricelist[idx].min == tmp:
55 raise Exception("the price range is not continuous!")
56 tmp = pricelist[idx].max
57 if tmp < MAX_INT:
58 raise Exception("the price range is Incomplete !")
59 print("pricelist is qualified.")
60 return True
61
62
63 # 初始化价格区间
64 def initPriceBrand():
65 pricelist.append(PriceRange(5, 0, 10))
66 pricelist.append(PriceRange(6, 10, 20))
67 pricelist.append(PriceRange(7, 20, 30))
68 pricelist.append(PriceRange(8, 30, 40))
69 pricelist.append(PriceRange(9, 40, 50))
70 pricelist.append(PriceRange(10, 50))
71
72
73 if __name__ == "__main__":
74 initPriceBrand()
75 verifyPriceBrand()
76 costlist = [5, 20, 80, 30, 10]
77 print(caculate(costlist))
















