关于#python#的问题:程实操题:商店不时会根据情况举行促销活动

程实操题:商店不时会根据情况举行促销活动,例如每满200元减15元、每满300元减25元之类的等等;此外,还有一种无门槛代金券,例如10元、15元、20元……请编写一个通用的优惠结算函数,由主程序调用函数对用户的商品计算出优惠后实付金额。测试运行程序时,需至少用到两种不同的满减和代金券。


def calculate_total(items, discounts):
    total = sum([item['price'] for item in items])
    for discount in discounts:
        if discount['type'] == '满减':
            if total >= discount['full']:
                total -= discount['reduce']
        elif discount['type'] == '代金券':
            total -= discount['value']
    return total

items = [
    {'name': '香蕉', 'price': 3},
    {'name': '橙子', 'price': 2},
]

discounts = [
    {'type': '满减', 'full': 200, 'reduce': 15},
    {'type': '满减', 'full': 300, 'reduce': 25},
    {'type': '代金券', 'value': 10},
    {'type': '代金券', 'value': 20},
]

total = calculate_total(items, discounts)
print('原价: {} 元'.format(sum([item['price'] for item in items])))
print('优惠后要支付的金额: {} 元'.format(total))