-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckout.py
51 lines (44 loc) · 1.54 KB
/
checkout.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Checkout:
class Discount:
def __init__(self, nbrItems, price):
self.nbrItems = nbrItems
self.price = price
def __init__(self):
self.items = {}
self.discounts = {}
self.prices = {}
def addPrice(self, item, price):
self.prices[item] = price
def addItem(self, item):
if item not in self.prices:
raise Exception("Item has not price")
if item in self.items:
self.items[item] += 1
else:
self.items[item] = 1
def calculateTotal(self):
total = 0
for item, cnt in self.items.items():
total += self.calculateItemTotal(item, cnt)
return total
def calculateItemTotal(self, item, cnt):
total = 0
if item in self.discounts:
discount = self.discounts[item]
if cnt >= discount.nbrItems:
total += self.calculateItemDiscountedTotal(item, cnt, discount)
else:
total += self.prices[item] * cnt
else:
total += self.prices[item] * cnt
return total
def calculateItemDiscountedTotal(self, item, cnt, discount):
total = 0
nbrOfDiscount = cnt / discount.nbrItems
total += nbrOfDiscount * discount.price
remainings = cnt % discount.nbrItems
total += remainings * self.prices[item]
return total
def addDiscount(self, item, nbrOfItems, price):
discount = self.Discount(nbrOfItems, price)
self.discounts[item] = discount