You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ortools背包算法报错:KNAPSACK_DYNAMIC_PROGRAMMING_SOLVER属性不存在

解决ortools 9.8+版本背包算法AttributeError问题

ortools 9.8+版本对KnapsackSolver的枚举类型做了重构,旧版本中使用的KNAPSACK_DYNAMIC_PROGRAMMING_SOLVER常量已被移除,替换为枚举类SolverType下的成员。以下是适配当前版本的完整代码示例:

from ortools.algorithms.python import knapsack_solver

def main():
    # 示例数据:物品价值、物品重量、背包容量
    values = [360, 83, 59, 130, 431, 67, 230, 52, 93, 125, 670, 892, 600, 38, 48, 147,
              78, 256, 63, 17, 120, 164, 432, 35, 92, 110, 22, 42, 50, 323, 514, 28,
              87, 73, 78, 15, 26, 78, 210, 36, 85, 189, 274, 43, 33, 10, 19, 389, 276, 312]
    weights = [[7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, 36, 3, 8, 15, 42, 9, 0,
                42, 47, 52, 32, 26, 48, 55, 6, 29, 84, 2, 4, 18, 56, 7, 29, 93, 44, 71,
                3, 86, 66, 31, 65, 0, 79, 20, 65, 52, 13]]
    capacities = [850]

    # 初始化求解器,使用新版本的枚举类型
    solver = knapsack_solver.KnapsackSolver(
        knapsack_solver.KnapsackSolver.SolverType.DYNAMIC_PROGRAMMING,
        'KnapsackExample'
    )

    solver.init(values, weights, capacities)
    computed_value = solver.solve()

    # 输出求解结果
    packed_items = []
    packed_weights = []
    total_weight = 0
    print(f'Total value: {computed_value}')
    for i in range(len(values)):
        if solver.best_solution_contains(i):
            packed_items.append(i)
            packed_weights.append(weights[0][i])
            total_weight += weights[0][i]
    print(f'Total weight: {total_weight}')
    print(f'Packed items: {packed_items}')
    print(f'Packed weights: {packed_weights}')

if __name__ == '__main__':
    main()

当前版本支持的求解器类型枚举:

  • SolverType.BRANCH_AND_BOUND:分支定界算法,适合精确求解较大规模问题
  • SolverType.GREEDY:贪心算法,速度快但可能无法得到最优解
  • SolverType.DYNAMIC_PROGRAMMING:动态规划算法,适合中等规模的0-1背包问题

内容的提问来源于stack exchange,提问作者Time

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 09:52:55