问题描述
我想在我的递归背包中得到一个真正的索引,以了解拿走了哪些物品。我很困惑如何获得真正的索引,这是我的代码
items = ['1','2','3','4','5','6']
price = [50,100,120,50,120]
weight = [10,20,30,5,70]
capacity = 60
n = len(price)
table = [[0 for i in range(capacity + 1)] for j in range(n + 1)]
things = []
def knapsack(weight,price,capacity,n):
if n == 0 or capacity == 0:
return 0
if table[n][capacity] != 0:
return table[n][capacity]
if weight[n - 1] <= capacity:
table[n][capacity] = max(price[n - 1] + knapsack(weight,capacity - weight[n - 1],n - 1),knapsack(weight,n - 1))
return table[n][capacity]
elif weight[n - 1] > capacity:
table[n][capacity] = knapsack(weight,n - 1)
return table[n][capacity]
print(knapsack(weight,n))
value = knapsack(weight,n)
for i in range(len(weight),-1):
if value > 0:
value = value-price[i-1]
things.append(i)
things.sort()
print(f"\n{things}")
for data in things:
print(f"\nItems_{items[data-1]}\nWeight : {weight[data-1]}\nPrice : {price[data-1]}")
然后“东西”的值现在是 [3,4,6] 但真正的值是 [1,2,5]。谁能帮我解决这个问题?如何获取索引[1,5]
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)