背包问题(优化后无法正常工作)

问题描述 投票:0回答:1

我正在研究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,

更多测试用例:https://people.sc.fsu.edu/~jburkardt/datasets/knapsack_01/knapsack_01.html

python algorithm dynamic-programming knapsack-problem
1个回答
0
投票
这里的问题是,您需要通过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)]

© www.soinside.com 2019 - 2024. All rights reserved.