背包约束python

背包约束python,python,algorithm,knapsack-problem,Python,Algorithm,Knapsack Problem,假设我有一个代表篮球运动员的元组列表,以及他们的姓名、位置、成本和他们的预测分数 listOfPlayers = [ ("Player1","PG",Cost,projectedPoints), ("Player2","PG",Cost,projectedPoints), ("Player3","SG",Cost,projectedPoints), ("Play

假设我有一个代表篮球运动员的元组列表,以及他们的姓名、位置、成本和他们的预测分数

listOfPlayers = [
                 ("Player1","PG",Cost,projectedPoints),
                 ("Player2","PG",Cost,projectedPoints),
                 ("Player3","SG",Cost,projectedPoints),
                 ("Player4","SG",Cost,projectedPoints),
                 ("Player5","SF",Cost,projectedPoints),
                 ("Player6","SF",Cost,projectedPoints),
                 ("Player7","PF",Cost,projectedPoints),
                 ("Player8","PF",Cost,projectedPoints),
                 ("Player9","C",Cost,projectedPoints),
                 ("Player10","C",Cost,projectedPoints) 
                ]
假设所有名称、成本和投影点都是可变的

我有一个传统的背包问题,他们可以根据给定的重量对背包进行分类和打包。但这并不能说明职位的原因。
我想知道是否有办法编辑背包代码,使其只包含每个位置中的一个,即(pg、sg、sf、pf、c)

一个传统的0/1背包能做到这一点吗?还是我需要换成其他的东西?

这就是所谓的“多项选择背包问题”

您可以使用类似于0/1背包问题的动态规划解决方案的算法

0/1背包问题的解如下:(来源)

m[i,w]
定义为重量小于或等于
w
时,使用小于或等于
i
的项目可获得的最大值
我们可以递归地定义
m[i,w]
,如下所示:

m[i, w] = m[i-1, w] if w_i > w   (new item is more than current weight limit)
m[i, w] = max(m[i-1, w], m[i-1, w-w_i] + v_i) if w_i <= w.
因此,假设我们有:

Name     Position  Cost  Points
Player1  PG        15    5
Player2  PG        20    10
Player3  SG        9     7
Player4  SG        8     6
然后我们有两个位置“PG”和“SG”,每个位置有两个选择

因此,对于位置“PG”(在
i=1
),我们将有:

m[i, c] = max(m[i-1, c],
              m[i-1, c-15] + 5    if 15 <= c, otherwise 0,
              m[i-1, c-20] + 10   if 20 <= c, otherwise 0)
m[i, c] = max(m[i-1, c],
              m[i-1, c-9] + 7    if 9 <= c, otherwise 0,
              m[i-1, c-8] + 6    if 8 <= c, otherwise 0)

首先,杜克林的回答很好。我没有评论的特权,所以我正在写一个答案。这实际上是一个“多项选择背包问题”。我实现了一个此类问题,并在Online Judge中运行了它,在那里成功地执行了它。Dukeling算法的唯一问题是它不会考虑前一组项目中的至少一个项目。因此,从上面:

m[i, c] = max(m[i-1, c],
              m[i-1, c-15] + 5    if 15 <= c, otherwise 0,
              m[i-1, c-20] + 10   if 20 <= c, otherwise 0)`
对于
i=2
(“SG”):

m[i,c]=max(m[i-1,c],

m[i-1,c-9]+7如果9我假设(但不知道具体如何)可以用标准算法的变体来解决背包问题。由于标准算法是基于,可以在多项式时间内找到解决方案。因此我建议去掉标记
np
:)@Bas Swinckels只是为了澄清,背包问题不能在多项式时间内求解。它肯定是np完全的。动态编程的复杂性取决于RHS(即O(b)),因此该算法以伪多项式时间运行:您有用于此的python实现吗?您有用于此的完整python实现吗?
m[i, c] = max(m[i-1, c],
              m[i-1, c-15] + 5    if 15 <= c, otherwise 0,
              m[i-1, c-20] + 10   if 20 <= c, otherwise 0)`
m[i, c] = max(m[i-1, c],
          m[i-1, c-15] + 5    if 15 <= c and  m[i-1, c-15] != 0, otherwise 0,
          m[i-1, c-20] + 10   if 20 <= c and  m[i-1, c-20] != 0, otherwise 0)
m[i, c] = max(m[i-1, c],
          m[i-1, c-9] + 7    if 9 <= c and m[i-1, c-9] != 0, otherwise 0,
          m[i-1, c-8] + 6    if 8 <= c and m[i-1, c-8] != 0, otherwise 0)