Python 最大化背包中的物品数量

Python 最大化背包中的物品数量,python,arrays,algorithm,knapsack-problem,Python,Arrays,Algorithm,Knapsack Problem,问题 给定n重量{w1,w2,…,wn},以及容量C的背包,填充背包时,优先级为背包中填充的物品数量。有关示例,请参考下面的示例 如果发生碰撞,即2个或多个具有相同长度的权重子集,则选择权重最大的一个 我还应该通过删除拾取的权重来重复相同的过程,直到权重列表为空 示例 1. Sort the weights list 2. Until the weights list is empty, iterate through the weights, 3. for i in weights:

问题

给定
n
重量
{w1,w2,…,wn}
,以及容量
C
的背包,填充背包时,优先级为背包中填充的物品数量。有关示例,请参考下面的示例

如果发生碰撞,即2个或多个具有相同长度的权重子集,则选择权重最大的一个

我还应该通过删除拾取的权重来重复相同的过程,直到权重列表为空

示例

1. Sort the weights list
2. Until the weights list is empty, iterate through the weights,
3. for i in weights:
       for j in weights[i:]:           (selection the list right of index i)
           pass
4. In a window fashion keep growing the window by adding elements into the window when the window weight is <= C, at the same time keeping track of the maximum window size, in case if the window sizes are equal, pick the window with more weight.
5. Remove the items from the weight array that are in the window selected from the above process and print it.
6. Go-to step 2
鉴于

weights = {60, 30, 45, 55, 100}
C = 100
然后,填充容量为100的背包的最佳方法如下所示,忽略使用单个物品填充背包的所有方法,因为子集的长度将为1

1. 60 + 30 = 90,          subset = {60, 30}, length = 2
2. 55 + 45 = 95,          subset = {55, 45}, length = 2
3. 60 + 45 = 106 > 100
4. 60 + 55 = 115 > 100
5. 30 + 45 = 75           subset = {30, 45}, length = 2
.
.
.
etc.
在上述两个选项中,选择第二个选项,因为它具有更大的权重

因此,应清空权重列表的步骤如下:

Step 1: Input: {60, 30, 45, 55, 100}, Selection: {55, 45}
Step 2: Input: {60, 30, 100},         Selection: {60, 30}
Step 3: Input: {100},                 Selection: {100}
解决方案伪代码

1. Sort the weights list
2. Until the weights list is empty, iterate through the weights,
3. for i in weights:
       for j in weights[i:]:           (selection the list right of index i)
           pass
4. In a window fashion keep growing the window by adding elements into the window when the window weight is <= C, at the same time keeping track of the maximum window size, in case if the window sizes are equal, pick the window with more weight.
5. Remove the items from the weight array that are in the window selected from the above process and print it.
6. Go-to step 2
1。对权重列表进行排序
2.直到权重列表为空,遍历权重,
3.对于i,重量:
对于权重中的j[i:]:(选择索引i的列表右侧)
通过
4.在窗口方式中,当窗口权重增加时,通过向窗口中添加元素来保持窗口的增长