python實現分段計費模式下的每日費用計算

公司的面試題,已知每日用電量,求分段計費模式下計算每日的電費,當初作的時候遇到一個小坑,沒考慮單日用電量跨越兩個以上計費區間這種狀況,python

如今把這道題用新學的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))
相關文章
相關標籤/搜索