输出购买物品的收据。投入:
<barcode>:<name>:<price>行格式的文本文件中找到。<barcode>:<min_quantity>:<discount>格式的折扣规则,这意味着购买超过min_quantity的barcode项目会给您一个discount (作为折扣百分比/1)。处理大量输入的可读代码
Products:
- 123:banana:0.5
- 789:apple:0.4
Discounts:
- 123:2:0.2 # Meaning buying 2 bananas will add a 20% discount
Purchases:
- [123,123] # Bought 2 bananas
Output:
- [('banana', 2, 0.8)]下面代码中可能出现的问题
从start_process函数开始读取代码时,最好能理解代码
class Product:
def __init__(self, barcode: int, name: str, price: float):
self.bardcode = barcode
self.name = name
self.price = price
@classmethod
def parse_product(cls, product_line: str):
name, barcode_str, price_str = product_line.split(':')
price = float(price_str)
barcode = int(barcode_str)
return cls(barcode, name, price)
class Products:
def __init__(self):
self.products = {} # Type: Dict<int, Product>
def add_product(self, product: Product):
self.products[product.bardcode] = product
def get_product(self, product_barcode):
return self.products[product_barcode]
@classmethod
def parse_products(products_cls, products_path: str):
products = products_cls()
with open(products_path) as products_lines:
for product_line in products_lines:
product = Product.parse_product(product_line)
products.add_product(product)
return products
class ProductPurchase:
def __init__(self, barcode: int, quantity = 1, discount = 0.0):
self.barcode = barcode
self.quantity = quantity
self.discount = discount
class DiscountRule:
def __init__(self, product_barcode: int, min_quantity: int, discount_amount: float):
self.product_barcode = product_barcode
self.min_quantity = min_quantity
self.discount_amount = discount_amount
@classmethod
def parse(cls, discount_rule: str):
barcode_str, min_quantity_str, discount_amount_str = discount_rule.split(':')
return cls(int(barcode_str), int(min_quantity_str), float(discount_amount_str))
class DiscountRules:
def __init__(self):
self.dicounts = {} # Type: Dict<int, DiscountRule>
def add_discount(self, discount: DiscountRule):
self.dicounts[discount.product_barcode] = discount
def apply_discount(self, purchase: ProductPurchase):
if purchase.barcode not in self.dicounts:
return
discount = self.dicounts[purchase.barcode]
if purchase.quantity < discount.min_quantity:
return
purchase.discount = discount.discount_amount
@classmethod
def parse_discount_rules(cls, rules_path: str):
rules = cls()
with open(rules_path) as rules_lines:
for rule_line in rules_lines:
rule = DiscountRule.parse(rule_line)
rules.add_discount(rule)
return rules
class Purchases:
def __init__(self):
self.purchases = {} # Type: Dict<int, ProductPurchase>
def add_purchase(self, purchased_barcode: int):
if purchased_barcode in self.purchases:
self.purchases[purchased_barcode].quantity += 1
else:
self.purchases[purchased_barcode] = ProductPurchase(purchased_barcode)
def get_purchases(self):
for purchase in self.purchases.values():
yield purchase
class Checkout:
def __init__(self, purchases: Purchases, products: Products, discount_rules: DiscountRules):
self.purchases = purchases
self.products = products
self.discount_rules = discount_rules
def check_out(self):
result = []
for purchase in self.purchases.get_purchases():
self.discount_rules.apply_discount(purchase)
product = self.products.get_product(purchase.barcode)
price = _calculate_price(product.price, purchase.quantity, purchase.discount)
result.append((product.name, purchase.quantity, price))
return result
def _calculate_price(price, quantity, discount):
return str(round(price * quantity * (1.0 - discount), 2))
def start_process(products_paths: str, discounts_path: str, scanner_input):
purchases = Purchases()
for purchased_barcode in scanner_input:
purchases.add_purchase(purchased_barcode)
products = Products.parse_products(products_paths)
discount_rules = DiscountRules.parse_discount_rules(discounts_path)
checkout = Checkout(purchases, products, discount_rules)
return checkout.check_out()发布于 2021-03-27 21:03:05
这是我建议的最后一个版本:
from typing import Iterable, Dict
class Product:
def __init__(self, barcode: int, name: str, price: float):
self.barcode = barcode
self.name = name
self.price = price
self.discounts = []
@classmethod
def parse_product(cls, product_line: str):
barcode, name, price = product_line.split(':')
return cls(int(barcode), name, float(price))
def add_discount(self, discount: 'DiscountRule'):
self.discounts.append(discount)
class Products(dict):
def __init__(self, *args, **kwargs):
super(Products, self).__init__(*args, **kwargs)
def add_product(self, product: Product):
self[product.barcode] = product
@classmethod
def parse_products(cls, products_path: str, discount_rules: 'Dict[int, DiscountRule]'):
products = cls()
with open(products_path) as products_lines:
for product_line in products_lines:
product = Product.parse_product(product_line)
if product.barcode in discount_rules:
product.add_discount(discount_rules[product.barcode])
products.add_product(product)
return products
class ProductPurchase:
def __init__(self, product: Product, quantity: int = 1):
self.product = product
self.quantity = quantity
@property
def discount(self):
total_discount = None
for discount in self.product.discounts:
if self.quantity >= discount.min_quantity:
if total_discount is None:
total_discount = 0
total_discount += discount.discount_amount
return total_discount
def purchase(self, quantity: int = 1):
self.quantity += quantity
@property
def discounted_price(self):
return round(self.product.price * self.quantity * (1.0 - self.discount), 2)
class DiscountRule:
def __init__(self, product_barcode: int, min_quantity: int, discount_amount: float):
self.product_barcode = product_barcode
self.min_quantity = min_quantity
self.discount_amount = discount_amount
@classmethod
def parse(cls, discount_rule: str):
barcode_str, min_quantity_str, discount_amount_str = discount_rule.split(':')
return cls(int(barcode_str), int(min_quantity_str), float(discount_amount_str))
@classmethod
def parse_discount_rules(cls, rules_path: str) -> 'Iterable[int, DiscountRule]':
with open(rules_path) as rules_lines:
for rule_line in rules_lines:
discount_rule = DiscountRule.parse(rule_line)
yield discount_rule.product_barcode, discount_rule
class Purchases(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def purchase(self, product: Product):
if product.barcode in self:
self[product.barcode].purchase()
else:
self[product.barcode] = ProductPurchase(product)
class ShoppingCart:
def __init__(self, purchases: Purchases, products: Products):
self.purchases = purchases
self.products = products
@classmethod
def init_from_files(cls, products_path: str, discounts_path: str, scanner_input: list):
discount_rules = DiscountRule.parse_discount_rules(discounts_path)
products = Products.parse_products(products_path, dict(discount_rules))
purchases = Purchases()
for purchased_barcode in scanner_input:
purchases.purchase(products[purchased_barcode])
return cls(purchases, products)
if __name__ == "__main__":
cart = ShoppingCart.init_from_files("products.txt", "discounts.txt", [123, 123])
print("TICKET")
for purchase in cart.purchases.values():
print("%s x %s | %s€" % (purchase.quantity, purchase.product.name, purchase.discounted_price))
print("------")以及带有注释的代码:
from typing import Iterable, List
class Product:
def __init__(self, barcode: int, name: str, price: float):
self.barcode = barcode # bardcode seems a typo for barcode
self.name = name
self.price = price
self.discounts = []
@classmethod
def parse_product(cls, product_line: str):
barcode, name, price = product_line.split(':')
"""price = float(price_str)
barcode = int(barcode_str) >>> un-needed in two steps """
return cls(int(barcode), name, float(price))
def add_discount(self, discount: 'DiscountRule'):
self.discounts.append(discount)
class Products(dict):
def __init__(self, *args, **kwargs):
super(Products, self).__init__(*args, **kwargs)
def add_product(self, product: Product):
self[product.barcode] = product
"""def get_product(self, product_barcode):
return self[product_barcode]
>>> no need for this method, the dict already implements a get
"""
@classmethod
def parse_products(cls, products_path: str):
"""stick to the cls naming convention
since it is a class method from the Products class, it is trivial that it is a product_cls
"""
products = cls()
with open(products_path) as products_lines:
for product_line in products_lines:
product = Product.parse_product(product_line)
products.add_product(product)
return products
class ProductPurchase:
def __init__(self, product: Product, quantity: int = 1): # >>> type hinting missing
self.product = product
self.quantity = quantity
# self.discount = discount
"""
>>> instead of storing a hard copy of the discount, which might get corrupted
if the discount or quantity change, use a property and compute it live
"""
@property
def discount(self):
""" computes the discount, accepts multiple discounts per product now """
total_discount = None
for discount in self.product.discounts:
if self.quantity >= discount.min_quantity:
if total_discount is None:
total_discount = 0
total_discount += discount.discount_amount
return total_discount
def purchase(self, quantity: int = 1):
""" provide a nice interface for modifying the quantity """
self.quantity += quantity
@property
def discounted_price(self):
return round(self.product.price * self.quantity * (1.0 - self.discount), 2)
class DiscountRule:
def __init__(self, product_barcode: int, min_quantity: int, discount_amount: float):
self.product_barcode = product_barcode
self.min_quantity = min_quantity
self.discount_amount = discount_amount
@classmethod
def parse(cls, discount_rule: str):
barcode_str, min_quantity_str, discount_amount_str = discount_rule.split(':')
return cls(int(barcode_str), int(min_quantity_str), float(discount_amount_str))
@classmethod
def parse_discount_rules(cls, rules_path: str) -> 'Iterable[DiscountRule]':
with open(rules_path) as rules_lines:
for rule_line in rules_lines:
yield DiscountRule.parse(rule_line)
@classmethod
def add_discounts_to_products(cls, discounts: 'Iterable[DiscountRule]', products: Products):
for discount in discounts:
if discount.product_barcode in products:
products[discount.product_barcode].add_discount(discount)
class Purchases(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def purchase(self, product: Product): # work with objects! not with keys which refer to objects
if product.barcode in self:
self[product.barcode].purchase()
else:
self[product.barcode] = ProductPurchase(product)
"""def get_purchases(self):
for purchase in self.values():
yield purchase
>>> not needed since now the interface is the actual dict
"""
class ShoppingCart: # a more meaningful name to the object, check_out is an action/method
def __init__(self, purchases: Purchases, products: Products):
self.purchases = purchases
self.products = products
# self.discount_rules = discount_rules >>> not needed anymore
def check_out(self) -> Iterable:
""" return an iterable instead of a list, the caller can then do whatever xhe wants """
for purchase in self.purchases.values():
yield purchase.product.name, purchase.quantity, purchase.discounted_price
@classmethod
def init_from_files(cls, products_path: str, discounts_path: str, scanner_input: list):
# get products from products_path
products = Products.parse_products(products_path)
# get discount_rules from discount_path
discount_rules = DiscountRule.parse_discount_rules(discounts_path)
DiscountRule.add_discounts_to_products(discount_rules, products)
purchases = Purchases()
for purchased_barcode in scanner_input:
purchases.purchase(products[purchased_barcode])
return cls(purchases, products)
"""def get_checkout(products_paths: str, discounts_path: str, scanner_input):
>>> if all the code is using objects, why have a random function and not use those objects?
"""
if __name__ == "__main__":
cart = ShoppingCart.init_from_files("products.txt", "discounts.txt", [123, 123])
print(list(cart.check_out()))发布于 2021-03-28 14:50:14
因为您正在处理CSV数据,而且如果您有一个结构良好的文件,就没有必要重新发明轮子并自己进行解析。Python已经有了一个用于此目的的库:csv - CSV文件读写。当然,一个个人的和极简的实现能够比一个已经建立并经过时间证明的模块表现得更好,这并不是不可能的,但这是值得怀疑的。但你可以自己测试。
另一个更明显的选择是使用熊猫。将数据导入dataframe,可以根据计算结果进一步操作该数据。
你还有一个选择:数据库。您可以使用sqlite模块并将文件导入到表中。我认为这个选择很适合你的目的。您可以通过几个联接完成工作,并可能根据需要进行一些子选择。但在这里,这只是您需要的3个表的一个非常基本的连接。
SQLite可以批量导入CSV文件,但是您需要为此调用shell。参见例如:https://wizardforcel.gitbooks.io/sqlite-doc-en/content/30.html
注意:数据库文件甚至不需要存储在磁盘上,您可以创建一个内存中的DB,在程序执行后被释放。但是,如果您有大型数据集,并且担心内存消耗,那么请使用DB文件。如果您在Linux上,可以在/tmp上使用临时文件,它通常是tmpfs (=快速数据访问)。
无论哪种方式,当所有数据都已导入时,批量执行计算(回扣)会更容易。您可以创建视图、临时表等。如果需要变得更加复杂,则可以使用Python混合使用,或者选择一个支持存储过程的数据库来处理更复杂的计算。
我不认为你选择的方法是最佳的。至少我建议您将编码中的这两个关注点分开:数据的导入和数据的转换。我的建议是重新考虑可用于这项工作的工具。在我看来,如果您选择DB方法,您可以抛弃这些类,并大大简化工作。
https://codereview.stackexchange.com/questions/258775
复制相似问题