I will be happy to get some help.
I have the following problem:
I\'m given a list of numbers seq
and a target number and I need to write 2 thing
This is how I'd write the subset_sum
:
def subset_sum(seq, target):
if target == 0:
return True
for i in range(len(seq)):
if subset_sum(seq[:i] + seq[i+1:], target - seq[i]):
return True
return False
It worked on a couple of examples:
>>> subset_sum([-1,1,5,4], 0))
True
>>> subset_sum([-1,1,5,4], 10)
True
>>> subset_sum([-1,1,5,4], 4)
True
>>> subset_sum([-1,1,5,4], -3)
False
>>> subset_sum([-1,1,5,4], -4)
False
To be honest I wouldn't know how to memoize it.
Old Edit: I removed the solution with any()
because after some tests I found out that to be slower!
Update: Just out of curiosity you could also use itertools.combinations:
from itertools import combinations
def com_subset_sum(seq, target):
if target == 0 or target in seq:
return True
for r in range(2, len(seq)):
for subset in combinations(seq, r):
if sum(subset) == target:
return True
return False
This can do better that the dynamic programming approach in some cases but in others it will hang (it's anyway better then the recursive approach).