我正在尝试使用 Python 3.x 使用动态编程(DP)方法解决背包问题。我的 TA 向我们指出了这个代码,以便我们抢占先机。我试图实现它,如下所示:
def take_input(infile):
f_open = open(infile, 'r')
lines = []
for line in f_open:
lines.append(line.strip())
f_open.close()
return lines
def create_list(jewel_lines):
#turns the jewels into a list of lists
jewels_list = []
for x in jewel_lines:
weight = x.split()[0]
value = x.split()[1]
jewels_list.append((int(value), int(weight)))
jewels_list = sorted(jewels_list, key = lambda x : (-x[0], x[1]))
return jewels_list
def dynamic_grab(items, max_weight):
table = [[0 for weight in range(max_weight+1)] for j in range(len(items)+1)]
for j in range(1,len(items)+1):
val= items[j-1][0]
wt= items[j-1][1]
for weight in range(1, max_weight+1):
if wt > weight:
table[j][weight] = table[j-1][weight]
else:
table[j][weight] = max(table[j-1][weight],table[j-1][weight-wt] + val)
result = []
weight = max_weight
for j in range(len(items),0,-1):
was_added = table[j][weight] != table[j-1][weight]
if was_added:
val = items[j-1][0]
wt = items[j-1][1]
result.append(items[j-1])
weight -= wt
return result
def totalvalue(comb):
#total of a combo of items
totwt = totval = 0
for val, wt in comb:
totwt += wt
totval += val
return (totval, -totwt) if totwt <= max_weight else (0,0)
#required setup of variables
infile = "JT_test1.txt"
given_input = take_input(infile)
max_weight = int(given_input[0])
given_input.pop(0)
jewels_list = create_list(given_input)
#test lines
print(jewels_list)
print(greedy_grab(jewels_list, max_weight))
bagged = dynamic_grab(jewels_list, max_weight)
print(totalvalue(bagged))
示例案例如下。它的格式为 line[0] = bag_max,line[1:] 的格式为(重量,值):
575
125 3000
50 100
500 6000
25 30
我对这段代码的逻辑感到困惑,因为它返回了一个元组,我不确定输出元组代表什么。我已经看了一段时间了,只是不明白代码指向我的是什么。任何帮助,将不胜感激。