Python 背包最大值的返回问题 #为了避免计算那些违反条款的项目,并且只输出满足条件且具有最大强度的ansewer def背包(w_列表、v_列表、i、i_w_1、v_w_1、w_帽): 计数器=真 最高值=无 if(i_w_1+w_list[i]在if分支中,您递
背包最大值的返回问题Python 背包最大值的返回问题 #为了避免计算那些违反条款的项目,并且只输出满足条件且具有最大强度的ansewer def背包(w_列表、v_列表、i、i_w_1、v_w_1、w_帽): 计数器=真 最高值=无 if(i_w_1+w_list[i]在if分支中,您递,python,algorithm,knapsack-problem,Python,Algorithm,Knapsack Problem,背包最大值的返回问题 #为了避免计算那些违反条款的项目,并且只输出满足条件且具有最大强度的ansewer def背包(w_列表、v_列表、i、i_w_1、v_w_1、w_帽): 计数器=真 最高值=无 if(i_w_1+w_list[i]在if分支中,您递归调用knapsack()两次,每次将结果分配给最高值,因此第一次调用的结果被遗忘。在else分支中,您调用knapsack()递归,但甚至不保存返回值。是的,我修改了它,我正在收集值,但它仍在打印相同的值,因为第一次调用的结果已被忘记,但我想
#为了避免计算那些违反条款的项目,并且只输出满足条件且具有最大强度的ansewer
def背包(w_列表、v_列表、i、i_w_1、v_w_1、w_帽):
计数器=真
最高值=无
if(i_w_1+w_list[i]在if
分支中,您递归调用knapsack()
两次,每次将结果分配给最高值,因此第一次调用的结果被遗忘。在else
分支中,您调用knapsack()
递归,但甚至不保存返回值。是的,我修改了它,我正在收集值,但它仍在打印相同的值,因为第一次调用的结果已被忘记,但我想收集第一次调用的结果,然后将其与每个后续调用进行比较,并在需要时更新值。我只是忽略了收集v值,因为给定的输入不需要它,但我仍然无法比较和更新最高的值。请有人帮助更正代码
#to avoid calculating those items which violates the terms and to only output , the ansewer satisfying the conditions , with the maximum weigth
def knapsack(w_list,v_list,i,i_w_1,v_w_1,w_cap):
counter = True
highest_value = None
if(i_w_1 + w_list[i] <= w_cap): #this is case when there is no problem
i_w_2 = i_w_1 #this is basically the evaluation part of the weights of new branch
v_w_2 = v_w_1
i_w_1 += w_list[i]
v_w_1 += v_list[i]
if(i == len(w_list) - 1):
print(i_w_1,v_w_1)
print(i_w_2,v_w_2)
max_value = max(v_w_1,v_w_2)
if counter or highest_value <= max_value:
counter = False
highest_value = max_value
return highest_value
highest_value = knapsack(w_list,v_list,i+1,i_w_1,v_w_1,w_cap)
highest_value = knapsack(w_list,v_list,i+1,i_w_2,v_w_2,w_cap)
elif(i_w_1 + w_list[i] > w_cap):#in this case we have to check which to evaluate and which to not
if(i_w_1 <= w_cap): #this is basically the evaluation part of the weight of new branch
i_w_2 = i_w_1
v_w_2 = v_w_1
if(i == len(w_list) - 1):
print(i_w_2,v_w_2)
return
knapsack(w_list,v_list,i+1,i_w_2,v_w_2,w_cap)
return highest_value
w_list = [1,2]
v_list = [10,20]
i = 0
i_w_1 = 0
v_w_1 = 0 #let us suppose the initial value associated with our weights be zero
w_cap = 3
highest_value = knapsack(w_list,v_list,i,i_w_1,v_w_1,w_cap)
print(highest_value)