我在subbset_sum问题
的变体上有以下函数def findFourPlus(itemCount, seq, goal):
goalDifference = float("inf")
closestPartial = []
subset_sum(itemCount, seq, goal, goalDifference, closestPartial, partial=[])
print(closestPartial)
def subset_sum(itemCount, seq, goal, goalDifference, closestPartial, partial):
s = sum(partial)
# check if the partial sum is equals to target
if(len(partial) == itemCount):
if s == goal:
print("FOUND YAA")
print(partial)
else:
if( abs(goal - s) < goalDifference):
#print(abs(goal-s), goalDifference, closestPartial)
goalDifference = abs(goal - s)
closestPartial[:] = partial
#print(abs(goal-s), goalDifference, closestPartial)
for i in range(len(seq)):
n = seq[i]
remaining = seq[i+1:]
subset_sum(itemCount, remaining, goal, goalDifference, closestPartial, partial + [n])
我之前的问题是,BESTPartial没有更新(返回一个空列表),即使我试图在subset_sum中改变它。现在已经解决了。现在我有一个类似的问题,我的目标差异也没有更新,因为它永远回归无限。
在subset_sum函数中,我正在尝试更新 goalDifference ,当我打印出一些测试输出时,它确实显示它正在更新,但我假设每次通过递归调用时,值再次丢失,每次都将 goalDifference 渲染回无限。
我该怎么做才能解决这个问题?