defMaxVal(contains,i,w,v):#four arg means the aviable space of container,the ith item to choose,and w and v means input of weights and valuesglobal callnums
callnums += 1if(i == 0):
return0if(contains < w[i]) else v[i]
without_i = MaxVal(contains,i-1,w,v)
if(contains < w[i]):
return without_i
else:
with_i = v[i]+MaxVal(contains-w[i],i-1,w,v)
return max(without_i,with_i)
动态规划版本:
defFastMaxVal(contains,i,w,v,memo):#memo is a dict recording all the partial solution we have getglobal callnums
callnums += 1if(i == 0):
return0if(contains < w[i]) else v[i]
if((contains,i) in memo):return memo[(contains,i)]
without_i= FastMaxVal(contains,i-1,w,v,memo)
if(contains < w[i]):
memo[(contains,i)] = without_i
return without_i
else:
with_i = v[i]+FastMaxVal(contains-w[i],i-1,w,v,memo)
memo[(contains,i)] = max(with_i,without_i)
return memo[(contains,i)]
defD_MaxVal(contains,i,w,v):return FastMaxVal(contains,i,w,v,{})
非递归版本
defBest_Maxval(contains,n,w,v,memo):assert(len(w)==len(v))
global infinity
for c in range(0,contains+1):
for i in range(0,n+1):
if(i==0):memo[(c,0)] = 0if(c<w[0])else v[0]
else:
without_i = memo[(c,i-1)] if((c,i-1) in memo) else0
with_i = v[i]+memo[(c-w[i],i-1)] if((c-w[i],i-1) in memo) else0
memo[(c,i)] = max(without_i,with_i)
return memo[(contains,n)]
defMaxVal3(contains,n,w,v):return Best_Maxval(contains,n,w,v,{})
test
w = [1,5,3,4,1,5,3,4,1,5,3,4,1,5,3,4,1,5,3,4,1,5,3,4,1,5,3,4]
w = w[0:23]
v = [15,10,9,5,15,10,9,5,15,10,9,5,15,10,9,5,15,10,9,5,15,10,9,5,15,10]
v = v[0:23]
start = time.clock()
callnums = 0
maxval = MaxVal3(95,len(w)-1,w,v)
end = time.clock()
print(maxval,'time:%d'%(end-start))
start = time.clock()
callnums = 0
maxval = D_MaxVal(95,len(w)-1,w,v)
end = time.clock()
print(maxval,'time:%d'%(end-start))
start = time.clock()
callnums = 0
maxval = MaxVal(95,len(w)-1,w,v)
end = time.clock()
print(maxval,'time:%d'%(end-start))
0-1背包的穷举解法.对于8个物品的调用了函数85次.def MaxVal(contains,i,w,v):#four arg means the aviable space of container,the ith item to choose,and w and v means input of weights and values global callnums callnum