3

I want to calculate the number of subsets of the array A = [2, 1, 1, 4] that sum to 2. There are 2 ways: (A[0]) and (A[1], A[2]). My code for computing this is:

 def W(number, index):
     A = [2, 1, 1, 4]
     if number < 0 or index < 0:
          return 0
     elif number==0:
          return 1
     else: 
          return W(number, index-1) + W(number - A[index], index)

Right now, when I call the function with W(2,3), I get 4 instead of 2. My problem is that my code also calculates the possibility (A[1], A[1]) and (A[2], A[2]). Is there any way to fix it while still using recursion?

1
  • See that when you use a number from an array (decrease your number by it) you don't want to reuse it again :) Commented Feb 22, 2022 at 21:16

2 Answers 2

3

The call to W(number - A[index], index) should be W(number - A[index], index - 1); otherwise, you allow for the possibility of double-counting an element in your subset sum.

Here is a code snippet that fixes this issue. For each element, we decide whether or not to add it to our sum. If the element allows our target to reach 0, we add 1 to our total count of possibilities, then recurse to see if there are any other ways to reach the target without adding the element we're currently examining:

A = [2, 1, 1, 4]

def W(number, index):
     if number < 0 or index < 0 :
          return 0
     elif number - A[index] == 0:
         return 1 + W(number, index - 1)
     else: 
          return W(number, index - 1) + W(number - A[index], index - 1)
          
print(W(1, 3)) # Prints 2
Sign up to request clarification or add additional context in comments.

8 Comments

Shouldn't that be 2 for W(4, 3), and 2 for W(5, 3)?
I think the order of the conditions can be changed. The first check is if number == 0: return 1 and then elif number < 0 or index < 0: return 0. This also works, but not sure about other test cases
W(1, 3) prints 1, but I think it should be 2 because A[1] and A[2] works.
Ah, yeah, you'll need to store the original target in that case. I'll fix shortly, I have to hop off for a bit.
Alright, edited.
|
2

This code seems to work for cases finding sums of 1..8:

A = [2, 1, 1, 4]

def W(number, index):
     if number == 0:
          return 1
     elif number < 0 or index < 0:
          return 0
     else:
         return W(number, index-1) + W(number - A[index], index - 1)

Testcases:

print(W(1, 3))
print(W(2, 3))
print(W(3, 3))
print(W(4, 3))
print(W(5, 3))
print(W(6, 3))
print(W(7, 3))
print(W(8, 3))

Output

2
2
2
2
2
2
2
1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.