|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +from collections import namedtuple |
| 4 | + |
| 5 | +Customer = namedtuple('Customer', 'name fidelity') |
| 6 | + |
| 7 | + |
| 8 | +class LineItem: |
| 9 | + |
| 10 | + def __init__(self, product, quantity, price): |
| 11 | + self.product = product |
| 12 | + self.quantity = quantity |
| 13 | + self.price = price |
| 14 | + |
| 15 | + def total(self): |
| 16 | + return self.price * self.quantity |
| 17 | + |
| 18 | + |
| 19 | +class Order: |
| 20 | + |
| 21 | + def __init__(self, customer, cart, promotion=None): |
| 22 | + self.customer = customer |
| 23 | + self.cart = list(cart) |
| 24 | + self.promotion = promotion |
| 25 | + |
| 26 | + def total(self): |
| 27 | + if not hasattr(self, '__total'): |
| 28 | + self.__total = sum(item.total() for item in self.cart) |
| 29 | + return self.__total |
| 30 | + |
| 31 | + def due(self): |
| 32 | + if self.promotion is None: |
| 33 | + discount = 0 |
| 34 | + else: |
| 35 | + discount = self.promotion(self) |
| 36 | + return self.total() - discount |
| 37 | + |
| 38 | + def __repr__(self): |
| 39 | + fmt = '<Order total: {:.2f} due: {:.2f}>' |
| 40 | + return fmt.format(self.total(), self.due()) |
| 41 | + |
| 42 | + |
| 43 | +# best promotion version 4 |
| 44 | +promos = [] |
| 45 | + |
| 46 | + |
| 47 | +def promotion(promo_func): |
| 48 | + promos.append(promo_func) |
| 49 | + return promo_func |
| 50 | + |
| 51 | + |
| 52 | +@promotion |
| 53 | +def fidelity_promo(order): |
| 54 | + """5% discount for customers with 1000 or more fidelity points""" |
| 55 | + return order.total() * 0.05 if order.customer.fidelity >= 1000 else 0 |
| 56 | + |
| 57 | + |
| 58 | +@promotion |
| 59 | +def bulk_item_promo(order): |
| 60 | + """10% discount for each LineItem with 20 or more units""" |
| 61 | + discount = 0 |
| 62 | + for item in order.cart: |
| 63 | + if item.quantity >= 20: |
| 64 | + discount += item.total() * 0.1 |
| 65 | + return discount |
| 66 | + |
| 67 | + |
| 68 | +@promotion |
| 69 | +def large_order_promo(order): |
| 70 | + """7% discount for orders with 10 or more distinct items""" |
| 71 | + distinct_items = {item.product for item in order.cart} |
| 72 | + if len(distinct_items) >= 10: |
| 73 | + return order.total() * 0.07 |
| 74 | + return 0 |
| 75 | + |
| 76 | + |
| 77 | +def best_promo(order): |
| 78 | + """Select best discount available""" |
| 79 | + return max(promo(order) for promo in promos) |
0 commit comments