我正在尝试实现this function来确定任何子集的总和是否等于目标值:
def subset_sum(numbers, target, partial=[]):
s = sum(partial)
# check if the partial sum is equals to target
if s == target:
print "sum(%s)=%s" % (partial, target)
if s >= target:
return # if we reach the number why bother to continue
for i in range(len(numbers)):
n = numbers[i]
remaining = numbers[i+1:]
subset_sum(remaining, target, partial + [n])
但是,我希望一旦遇到目标实例,该函数就可以“中断” /返回,这样它就不会继续寻找更多对象。
我已经尝试过了,但是仍然继续:
def subset_sum(numbers, target, partial=[]):
s = sum(partial)
# check if the partial sum is equals to target
if s == target:
print "sum(%s)=%s" % (partial, target)
return // should stop once reaches one instance
if s >= target:
return # if we reach the number why bother to continue
for i in range(len(numbers)):
n = numbers[i]
remaining = numbers[i+1:]
subset_sum(remaining, target, partial + [n])
答案 0 :(得分:0)
使subset_sum
返回布尔值:是否找到该子集。检查递归调用的结果。
def subset_sum(numbers, target, partial=[]):
s = sum(partial)
# check if the partial sum is equals to target
if s == target:
print "sum(%s)=%s" % (partial, target)
return True # should stop once reaches one instance
if s > target:
return False # if we reach the number why bother to continue
for i in range(len(numbers)):
n = numbers[i]
remaining = numbers[i+1:]
if subset_sum(remaining, target, partial + [n]):
return True
return False
更好的方法可能是返回答案(即partial
或None
。