代码
# 商品属性 ITEM = {‘ITEM0001‘: {‘name‘: ‘黄焖鸡‘, ‘price‘: 18}, ‘ITEM0013‘: {‘name‘: ‘肉夹馍‘, ‘price‘: 6}, ‘ITEM0022‘: {‘name‘: ‘凉皮‘, ‘price‘: 8} } # 打折商品列表 DISCOUNT_ITEM = (‘ITEM0001‘, ‘ITEM0022‘) # 满减优惠列表 BREAK_DISCOUNT = {30: 6} BREAK_PRICE_LIST = [30] # 打折优惠力度 CHARGE_PERCENT = 0.5 def bestCharge(order=None): """ 接收用户选择的菜品和数量, 计算汇总信息 :param order: list 用户订单数据 """ # 指定菜品半价(黄焖鸡,凉皮),省13元 totle_price = 0 # 商品总价 sale_price = 0 # 特定商品打折金额 order_menu = [] discount_names = [] for line in order: item, num = line.split(‘ x ‘) price = ITEM[item][‘price‘] name = ITEM[item][‘name‘] item_pay = int(num) * price totle_price += item_pay out_str = ‘{} x {} = {}元‘.format(name, num, item_pay) order_menu.append(out_str) if item in DISCOUNT_ITEM: sale_price += price * CHARGE_PERCENT discount_names.append(name) break_discount_price = 0 break_menu_str = ‘‘ # 判断最优的满减额度 for break_price in BREAK_PRICE_LIST: if break_price <= totle_price: break_discount_price = BREAK_DISCOUNT.get(break_price) break_menu_str = ‘满{}减{}元,省{}元‘.format(break_price, break_discount_price, break_discount_price) break # 输出结果 chargeOut(break_discount_price, sale_price, order_menu, discount_names, break_menu_str, totle_price) def chargeOut(break_discount_price, sale_price, order_menu, discount_names, break_menu_str, totle_price): """ 结果输出函数, 选取最优的优惠方式,两种优惠方式省钱一样多,使用满减优惠方式 :param break_discount_price: int 满减优惠总价 :param sale_price: int 打折商品优惠总价 :param order_menu: list 用户订单明细列表 :param discount_names: list 打折商品名称列表 :param break_menu_str: str 满减商品明细 :param totle_price: int 商品原价 :return: """ print(‘============= 订餐明细 =============‘) # 输出明细 for line in order_menu: print(line) print(‘-----------------------------------‘) if break_discount_price == sale_price == 0: discount = 0 elif break_discount_price >= sale_price: print(break_menu_str) discount = break_discount_price print(‘-----------------------------------‘) else: names = ‘,‘.join(discount_names) discount = sale_price print("""使用优惠:\n指定菜品半价({}),省{}元""".format(names, int(sale_price))) print(‘-----------------------------------‘) real_pay = totle_price - discount print(‘总计:{}元‘.format(int(real_pay))) print(‘===================================‘) if __name__ == ‘__main__‘: order = ["ITEM0013 x 5", "ITEM0022 x 1"] # order = ["ITEM0013 x 4", "ITEM0022 x 1"] # order = ["ITEM0013 x 4"] # order = ["ITEM0001 x 1", "ITEM0013 x 2", "ITEM0022 x 1"] bestCharge(order)
原文地址:https://www.cnblogs.com/jiuyang/p/12375390.html
时间: 2024-11-08 02:43:18