Find subarray that sums to given value in Python
<p>If I am given a subarray [1,2,3,4] and a value 8. I want to return the subarray [1,3,4]. I have a bug in my code and am not sure how to fix it since I am new to recursion. I have my Python code below. I am getting back the value [3,4] to print which is obviously not the correct answer. How do I get my first element in the array?</p>

<pre><code>def main():
    s = 0
    a = [1,2,3,4] # given array
    sa = [] # sub-array
    w = 8 # given weight
    d = False
    d, sa = checkForWeight(a,w,s,d,sa)
    print sa

def checkForWeight(a,w,s,d,sa):
    l = len(a)
    s += a[0]
    sa.append(a[0])
    if s == w:
        d = True
        return d, sa
    else:
        try:
            d, sa = checkForWeight(a[1:],w,s,d,sa)
            if d != True:
                d, sa = checkForWeight(a[2:],w,s,d,sa)
            else:
                return d, sa
        except:
            sa = [] # i put this here because I want to erase the incorrect array
    return d, sa
</code></pre>

<p>The immediate problem is that you append a[0] to sa at the top of the function, but later destroy that with the return value from a sub-call.  To patch this, add a clause before you return the final result:</p>

<pre><code>    except:
        sa = [] # i put this here because I want to erase the incorrect array
if d:
    sa = [a[0]] + sa
print "Leave: drop", d,sa
return d, sa
</code></pre>

<p>I do recommend that you follow the recommendations in the comments: instead of passing so much stuff around, concentrate on local control of partial solutions.</p>

<p>Try a solution two ways: with and without the current element.  Your recursive calls will look something like this:</p>

<pre><code>sa = checkForWeight(a[1:], w)         # Solutions without first element
    -- and --
sa = checkForWeight(a[1:], w-a[0])    # Solutions using first element

You don't have to return a success flag; if **sa** is None or empty, the call failed to find a solution.  If it succeeded, in the **w-a[0]** call, then you also need to prepend each solution in **sa** with **a[0]**.
</code></pre>

<p>Does this get you moving?</p>

python recursion sub-array