Python 我试图解决0/1背包问题,但我得到的输出是一样多的零
下面是针对0/1背包问题给出的代码,我在输出表中得到的零最多。我如何理解为什么会发生此问题以及如何解决此问题Python 我试图解决0/1背包问题,但我得到的输出是一样多的零,python,data-structures,dynamic-programming,knapsack-problem,Python,Data Structures,Dynamic Programming,Knapsack Problem,下面是针对0/1背包问题给出的代码,我在输出表中得到的零最多。我如何理解为什么会发生此问题以及如何解决此问题 item = 4 profit = [1, 2, 4, 5] weight = [5, 4, 8, 6] bag = 5 import numpy as np table=np.zeros([item,bag]) for j in range(bag): for i in range(len(weight)):
item = 4
profit = [1, 2, 4, 5]
weight = [5, 4, 8, 6]
bag = 5
import numpy as np
table=np.zeros([item,bag])
for j in range(bag):
for i in range(len(weight)):
if i==0 or j==0 :continue
elif j< weight[i]:
table[i][j] = table[i-1][j]
#print(i,j)
else:
table[i][j] =max((profit[i]+table[i-1][j-weight[i]]),
(table[i-1][j]))
print(table)
[[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 2.]
[ 0. 0. 0. 0. 2.]
[ 0. 0. 0. 0. 2.]]