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 things:
A recursive solution that returns
True
if there is a sum of a subsequence that equals the target number andFalse
otherwise. example:subset_sum([-1,1,5,4],0) # True subset_sum([-1,1,5,4],-3) # False
Secondly, I need to write a solution using what I wrote in the previous solution but now with memoization that uses a dictionary in which the keys are tuples:
(len(seq),target)
For number 1 this is what I got to so far:
def subset_sum(seq, target):
if target == 0:
return True
if seq[0] == target:
return True
if len(seq) > 1:
return subset_sum(seq[1:],target-seq[0]) or subset_sum(seq[1:],target)
return False
Not sure I got it right so if I could get some input I will be grateful.
For number 2:
def subset_sum_mem(seq, target, mem=None ):
if not mem:
mem = {}
key=(len(seq),target)
if key not in mem:
if target == 0 or seq[0]==target:
mem[key] = True
if len(seq)>1:
mem[key] = subset_sum_mem(seq[1:],target-seq[0],mem) or subset_sum_mem(seq[1:],target,mem)
mem[key] = False
return mem[key]
I can't get the memoization to give me the correct answer so I'd be glad for some guidance here.
Thanks for anyone willing to help!
This is how I'd write the
subset_sum
:It worked on a couple of examples:
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
: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).