微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

知道在递归背包问题python中拿走了哪些物品

如何解决知道在递归背包问题python中拿走了哪些物品

我想在我的递归背包中得到一个真正的索引,以了解拿走了哪些物品。我很困惑如何获得真正的索引,这是我的代码

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 举报,一经查实,本站将立刻删除。