def maxVal(w, v, i, aW):
global numCalls
numCalls += 1
print numCalls, 'maxVal called with: ', i, aW
if i == 0:
if w[i] <= aW: return v[i]
else: return 0
without_i = maxVal(w, v, i-1, aW)
if w[i] > aW:
return without_i
else:
with_i = v[i] + maxVal(w, v, i-1, aW - w[i])
return max(with_i, without_i)
def fastMaxVal(w, v, i, aW, m):
global numCalls
numCalls += 1
## print numCalls, 'fastMaxVal called with: ', i, aW
try: return m[(i, aW)]
except KeyError:
if i == 0:
if w[i] <= aW: return v[i]
else: return 0
without_i = fastMaxVal(w, v, i-1, aW, m)
if w[i] > aW:
return without_i
else:
with_i = v[i] + fastMaxVal(w, v, i-1, aW - w[i], m)
res = max(with_i, without_i)
m[(i, aW)] = res
return res
def maxVal0(w, v, i, aW):
m = {}
return fastMaxVal(w, v, i, aW, m)
##weights = [1, 5, 3, 4]
##vals = [15, 10, 9, 5]
##numCalls = 0
##res = maxVal(weights, vals, len(vals) - 1, 8)
##print 'max Val =', res, 'number of calls = ', numCalls
maxWeight = 40
w = [5,5,1,8,2,4,7,5,2,8,1,2,7,3,5,7,8,5,5,8,2,3,8,4,9]
v = [5,5,3,5,6,7,2,3,7,1,6,3,6,8,8,6,5,6,8,4,3,3,2,3,4]
numCalls = 0
res = maxVal0(w, v, len(v) - 1, maxWeight)
print 'max Val =', res, 'number of calls = ', numCalls