Python 背包问题(优化不正确)

Python 背包问题(优化不正确),python,algorithm,dynamic-programming,knapsack-problem,Python,Algorithm,Dynamic Programming,Knapsack Problem,为了解决背包问题,我正在编写Python代码 这是我的密码: import time start_time = time.time() #reading the data: values = [] weights = [] test = [] with open("test.txt") as file: W, size = map(int, next(file).strip().split()) for line in file: value, weight = map(int

为了解决背包问题,我正在编写Python代码

这是我的密码:

import time
start_time = time.time()
#reading the data:
values = []
weights = []
test = []
with open("test.txt") as file:

  W, size = map(int, next(file).strip().split())
  for line in file:
    value, weight = map(int, line.strip().split())
    values.append(int(value))
    weights.append(int(weight))

weights = [0] + weights
values = [0] + values

#Knapsack Algorithm:


hash_table = {}
for x in range(0,W +1):
  hash_table[(0,x)] = 0

for i in range(1,size + 1):
  for x in range(0,W +1):
    if weights[i] > x:
      hash_table[(i,x)] = hash_table[i - 1,x]
    else:
      hash_table[(i,x)] = max(hash_table[i - 1,x],hash_table[i - 1,x - weights[i]] + values[i])

print("--- %s seconds ---" % (time.time() - start_time))
这段代码工作正常,但在一个大文件上,我的程序由于RAM问题而崩溃

因此,我决定更改以下部分:

for i in range(1,size + 1):
  for x in range(0,W +1):
    if weights[i] > x:
      hash_table[(1,x)] = hash_table[0,x]
      #hash_table[(0,x)] = hash_table[1,x]
    else:
      hash_table[(1,x)] = max(hash_table[0,x],hash_table[0,x - weights[i]] + values[i])
      hash_table[(0,x)] = hash_table[(1,x)]
如您所见,我没有使用n行,而是只使用了两行(将第二行复制到第一行,以便重新创建以下代码行
hash_table[(i,x)]=hash_table[i-1,x]
),这应该可以解决RAM的问题

但不幸的是,它给了我一个错误的结果

我使用了以下测试用例:

190 6

50 56

50 59

64 80

46 64

50 75

5 17

Should get a total value of 150 and total weight of 190 using 3 items:

item with value 50 and weight 75,

item with value 50 and weight 59,

item with value 50 and weight 56,

更多测试用例:

这里的问题是,您需要在i上重置迭代中的所有值,但也需要x索引,因此,您可以使用另一个循环:

for i in range(1,size + 1):
  for x in range(0,W +1):
    if weights[i] > x:
      hash_table[(1,x)] = hash_table[0,x]
    else:
      hash_table[(1,x)] = max(hash_table[0,x],hash_table[0,x - weights[i]] + values[i])
  for x in range(0, W+1): # Make sure to reset after working on item i
    hash_table[(0,x)] = hash_table[(1,x)]

我最初认为缩进是错误的,但事实上,在循环结束后,您需要移动所有(I,x)对,否则else分支会干扰您,非常感谢!这有助于:)