You need to enable JavaScript to run this app. Python含普通/限量商品的简化背包最小剩余额代码排查
优惠活动
大模型
产品
解决方案
定价
更多

Python含普通/限量商品的简化背包最小剩余额代码排查

带库存约束的简化背包问题代码调试

问题前置说明

  • 场景:商店售卖两类商品
    • 普通商品:库存无上限,可任意数量购买
    • 限量商品:库存固定,最多按剩余数量购买
  • 目标:给定初始可支配金额,计算购买商品后的最小剩余金额,要求严格保留so_rich(迭代实现)、so_rich_recursive(递归实现)两个函数的原有签名,不得修改。
  • 测试基准配置:A(20美元,普通)、B(7美元,普通)、C(1美元,限量2件)
    • 输入金额45美元时,最优方案为6件B+2件C,剩余1美元
    • 输入金额61美元时,最优方案为2件A+3件B,剩余0美元

商品类基础定义

class Product:
    """ 
    A class to provide abstraction for products availabel in the system.
    unless the product is a Limited_product its supply is infinite
    """
    product_counter = 0

    ##### Part 1.1 #####
    def __init__(self, name, price):
        """ Constructor for initialization """
        self.name = name
        self.price = price
        self.id = Product.product_counter
        Product.product_counter += 1

    def __str__(self):
        """ returns a string representation of a product """
        return "<{}> {} - {}$".format(self.id, self.name, self.price)

    def __repr__(self):
        """ represents the class object as a string """
        return "PRODUCT <{}>".format(self.id)


class Limited_Product(Product):
    """
    A child class of the parent Product class
    Represents a Limited product where the quantity is depreceating
    """

    ##### Part 1.2 #####
    def __init__(self, name, price, amount):
        """ Constructor for initialization """
        super().__init__(name, price)
        self.amount = amount

    def __str__(self):
        """ returns a string representation of a limited product """
        return "<{}> {} - {}$ ({} left)".format(self.id, self.name, self.price, self.amount)

    def decrement_amount(self):
        """ decrement the amount of available product """
        self.amount -= 1

    def get_amount(self):
        """ returns the amount available from the product """
        return self.amount

现有代码的错误根因

迭代版so_rich的问题

  • 缺失「不购买当前商品」的分支逻辑:每次处理商品时,仅记录了购买商品后的剩余金额,完全没有保留"一件当前商品都不买"时的原有剩余金额,导致每次迭代都会覆盖之前的合法购买路径,后续计算时根本无法组合出不买某类商品的最优方案(比如测试用例1要求的不买A、只买B和C的组合)。
  • 剩余值记录时机错误:扣减金额前就把当前值加入集合,导致循环终止时最后那个扣完的剩余值被遗漏。比如商品价格7美元,当前剩余8美元,现有逻辑第一次把8加入集合,扣完剩1,因1<7循环终止,这个合法的剩余值1根本没被加入集合。
  • 限量商品分支没有枚举完整购买量:顺着库存扣到底,没有覆盖买0、1直到最大库存数的所有可能剩余值。

递归版so_rich_recursive的问题

  • 逻辑本质是贪心而非全枚举:现有逻辑会对当前商品找到能花掉最多钱的购买量,把剩下的钱传给下一层,相当于强制把当前商品能买的最大件数买完,完全没有组合多商品购买方案的能力,根本不可能得到全局最优解。
  • 同样缺失「不买当前商品」的分支,且循环边界错误:普通商品分支的循环判断写为product.price < tmp,等于商品价格时直接跳过,漏掉了刚好把钱花完的合法场景。

修复实现

迭代版修复要点

  • 处理每个商品时,首先把原有剩余值集合里的所有值加入临时集合(对应一件当前商品都不买的情况)
  • 遍历每个原有剩余值时,枚举从"买0件"到"最大可购买件数"的所有可能,把对应的剩余金额全部加入临时集合,再替换原有剩余值集合进入下一轮商品处理
  • 修正扣减和记录的顺序:先扣减金额,再把扣完的剩余值加入集合,避免遗漏终值

修复后的代码示例:

def so_rich(self, money):
    left = set([money])
    lst = list(self.warehouse.inventory.values())
    for product in lst:
        tmp_left = set()
        for m in left:
            # 记录一件不买的情况
            tmp_left.add(m)
            new_left = m
            if type(product) != Limited_Product:
                # 普通商品可无限购买直到钱不足
                while product.price <= new_left:
                    new_left -= product.price
                    tmp_left.add(new_left)
            else:
                # 限量商品受库存上限约束
                product_count = product.amount
                while product.price <= new_left and product_count > 0:
                    new_left -= product.price
                    tmp_left.add(new_left)
                    product_count -= 1
        left = tmp_left
    return min(left)

递归版修复要点

  • 递归时遍历当前商品所有可购买数量(从0到最大可买量),对每个购买量计算对应的剩余金额,把剩余金额传给下一层递归
  • 收集所有购买分支下的最小剩余金额,返回全局最小值
  • 修正循环边界,保证刚好花完钱的场景被覆盖

修复后的代码示例:

def so_rich_recursive(self, money):
    lst = list(self.warehouse.inventory.values())
    def helper(products, current_money):
        # 所有商品处理完成,返回当前剩余金额
        if not products:
            return current_money
        product = products[0]
        rest_products = products[1:]
        min_left = current_money
        # 计算当前商品最多能买的数量
        if type(product) == Limited_Product:
            max_buy = min(product.amount, current_money // product.price)
        else:
            max_buy = current_money // product.price
        # 枚举买0到最大件数的所有可能
        for buy_num in range(max_buy + 1):
            remain_money = current_money - buy_num * product.price
            current_min = helper(rest_products, remain_money)
            if current_min < min_left:
                min_left = current_min
        return min_left
    return helper(lst, money)

内容的提问来源于stack exchange,提问作者Isuru Madhushanka Samaranayake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.30 15:15:05