I have the following algorithm that solves the subset sum problem recursively:
def findSubset(alist, targ, i, sumsofar):
if sumsofar == targ:
return True
if i == len(alist):
return False
inc = findSubset(alist, targ, i+1, sumsofar+alist[i])
noninc = findSubset(alist, targ, i+1, sumsofar)
return inc or noninc
The algorithm works fine, but it only gives a boolean answer. So if I call it as so:
alist = [4, 6, 21, 29, 37, 50]
findSubset(alist, 76, 0, 0)
>>> True
But I would like it to return [4, 6, 29, 37]
Here is my attempt at altering the algorithm:
def findSubset(alist, targ, i, sumsofar, new):
if sumsofar == targ:
return new
if i == len(alist):
return []
inc = findSubset(alist, targ, i+1, sumsofar+alist[i], new.append(alist[i]))
noninc = findSubset(alist, targ, i+1, sumsofar, new)
return inc or noninc
Where it is used as so:
alist = [4, 6, 21, 29, 37, 50]
findSubset(alist, 76, 0, 0, [])
>>>AttributeError: 'NoneType' object has no attribute 'append'
What must I do to make it work, is it even possible?
return inc or nonionictoreturn inc if inc else noninc?append()modifies a list in place and returnsNone.