简体   繁体   English

Python中的01背包动态编程

[英]01 knapsack dynamic programming in python

def printtable(arr):
    for row in arr:
        print(row)
    return

items = [(3,2),(4,3),(5,4),(6,5)]
W = 5

arr = [[0]*(W+1)]*(len(items)+1)

for i in range(1,len(items)+1,1):
    val,wt = items[i-1]
    for w in range(1,W+1,1):
        if wt <= w:
            arr[i][w] = max(arr[i-1][w] , val + arr[i-1][w-wt])
        else:
            arr[i][w] = arr[i-1][w]

printtable(arr)

The output is: 输出为:

[0, 0, 3, 4, 6, 7]
[0, 0, 3, 4, 6, 7]
[0, 0, 3, 4, 6, 7]
[0, 0, 3, 4, 6, 7]
[0, 0, 3, 4, 6, 7]

I don't know what is the issue in this code ? 我不知道这段代码是什么问题? The values are wrong. 值是错误的。 But the logic in the code is correct. 但是代码中的逻辑是正确的。

Expected output is: 预期输出为:

0 0 0 0 0 0
0 0 3 3 3 3
0 0 3 4 4 7
0 0 3 4 5 7
0 0 3 4 5 7

The issue is in how you create the list of lists . 问题在于如何创建列表列表。 When you do - 当你做-

arr = [[0]*(W+1)]*(len(items)+1)

This creates a single inner list and each list in the outer list is a reference to the same list. 这将创建一个内部列表,外部列表中的每个列表都是对同一列表的引用。 Example to show this issue - 显示此问题的示例-

>>> a = [[0]*5]*5
>>> print(a)
[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]
>>> a[0][0] = 1
>>> print(a)
[[1, 0, 0, 0, 0],
 [1, 0, 0, 0, 0],
 [1, 0, 0, 0, 0],
 [1, 0, 0, 0, 0],
 [1, 0, 0, 0, 0]]

You should use list comprehension instead - 您应该改为使用列表理解-

arr = [[0 for _ in range(W+1)] for _ in range(len(items)+1)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM