def fastMaxVal(w, v, i, aW):
global numCalls
numCalls += 1
try: return m[(i, aW)]
except KeyError:
if i == 0:
if w[i] <= aW:
m[(i, aW)] = v[i]
return v[i]
else:
m[(i, aW)] = 0
return 0
without_i = fastMaxVal(w, v, i-1, aW)
if w[i] > aW:
m[(i, aW)] = without_i
return without_i
else:
with_i = v[i] + fastMaxVal(w, v, i-1, aW - w[i])
res = max(with_i, without_i)
m[(i, aW)] = res
return res
def maxVal0(w, v, i, aW):
m = {}
return fastMaxVal
weights = [1, 1, 5, 5, 3, 3, 4, 4]
vals = [15, 15, 10, 10, 9, 9, 5, 5]
numCalls = 0
res = maxVal0(weights, vals, len(vals) - 1, 8)
print ('max Val =', res, 'number of calls =', numCalls)
该程序约为01Knapsack问题。我使用决策树来解决问题。但是,我运行该程序并得到以下结果。
max Val =函数fastMaxVal位于0x03BB7390次数= 0
我的计划出了什么问题?
答案 0 :(得分:1)
在maxVal0
函数中,您将返回fastMaxVal
函数本身,而不是其调用结果。
我认为应该是这样的:
def maxVal0(w, v, i, aW):
m = {}
return fastMaxVal(w, v, i, aW)
此外,您的fastMaxVal
正在使用m
,但它不在其范围内。
答案 1 :(得分:0)
def fastMaxVal(w, v, i, aW, m):
global numCalls
numCalls += 1
try: return m[(i, aW)]
except KeyError:
if i == 0:
if w[i] <= aW:
m[(i, aW)] = v[i]
return v[i]
else:
m[(i, aW)] = 0
return 0
without_i = fastMaxVal(w, v, i-1, aW, m)
if w[i] > aW:
m[(i, aW)] = without_i
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, 1, 5, 5, 3, 3, 4, 4]
vals = [15, 15, 10, 10, 9, 9, 5, 5]
numCalls = 0
res = maxVal0(weights, vals, len(vals) - 1, 8)
print ('max Val =', res, 'number of calls =', numCalls)
我把右边放在上面。我将结果附在如下。
最大值= 48次呼叫= 50