商品折扣计算实现咨询:剩余商品按最低价计价问题
商品折扣计算:剩余商品最低价计价解决方案
首先先帮你理清现有代码里的几个小问题,再重点解决剩余商品的计价逻辑:
- 字典键拼写错误:你定义的商品字典里是
no_reqired_for_dis,但代码里写的是no_required_for_dis,少了一个字母i; - 循环重复计算折扣:你在for循环里每次都会执行
total_payment += total_pair * 250,这会导致同一个折扣部分被累加4次(对应4种商品),结果肯定不对; - 字典keys处理问题:
product[key]["no_reqired_for_dis"].keys()返回的是dict_keys对象,不能直接用[0]索引,需要转成列表或者用next(iter(...))获取第一个键。
接下来重点解决剩余商品的计价逻辑:要让剩余remaining_unit件商品的总价最低,核心思路是优先选取单价最低的商品来凑剩余数量,具体步骤如下:
- 整理所有已购商品的「单价-购买数量」信息,按单价从低到高排序;
- 遍历排序后的列表,依次从每个商品中拿取需要的数量(最多不超过该商品的购买量),直到凑够
remaining_unit件,累加对应的价格。
下面是修正后的完整代码:
product = { "shirt" : { "price" :300 , "no_reqired_for_dis" : {"3": ["shirt","pents","tshirt","shorts"],"discount_price" : 250}}, "pents" : { "price" :200 , "no_reqired_for_dis" : {"3": ["shirt","pents","tshirt","shorts"],"discount_price" : 250}}, "tshirt" : { "price" :150 , "no_reqired_for_dis" : {"3": ["shirt","pents","tshirt","shorts"],"discount_price" : 250}}, "shorts" : { "price" :100 , "no_reqired_for_dis" : {"3": ["shirt","pents","tshirt","shorts"],"discount_price" : 250}} } total_payment = 0 total_product = {"shirt" : 5,"pents":4,"tshirt":1,"shorts":1} total_item = sum(total_product.values()) # 提取折扣规则:满3件为一组,每组计价250 discount_group_size = 3 discount_price_per_group = 250 if total_item < discount_group_size: # 不够一组折扣,直接按原价计算所有商品 for item, count in total_product.items(): total_payment += count * product[item]["price"] else: # 计算折扣部分的总价 total_groups = total_item // discount_group_size total_payment += total_groups * discount_price_per_group # 计算剩余需要按原价计价的数量 remaining_unit = total_item % discount_group_size # 将已购商品按单价从低到高排序,优先选低价商品凑剩余数量 sorted_items = sorted( [(product[item]["price"], count) for item, count in total_product.items()], key=lambda x: x[0] ) # 累加剩余数量的最低总价 remaining_count = remaining_unit for price, count in sorted_items: if remaining_count <= 0: break # 取当前商品能贡献的数量:不超过剩余需求,也不超过购买量 take = min(remaining_count, count) total_payment += take * price remaining_count -= take print(total_payment) # 输出结果:250*3 + 100 + 150 = 1000,和你例子的预期一致
代码说明:
- 先判断总数量是否满足折扣门槛,不满足则直接按原价计算;
- 满足折扣条件时,先计算所有折扣组的总价;
- 通过排序优先选取低价商品凑剩余数量,确保剩余部分的总价最低;
- 遍历排序后的商品列表,每次取尽可能多的当前商品(不超过剩余需求和购买量),直到凑够剩余数量。
这样就能完美解决你困惑的剩余商品计价问题啦~
内容的提问来源于stack exchange,提问作者alex
相关产品推荐
相关产品推荐

