Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to calculate number of possibilities?

(this is homework) I want to calculate amount of ways getting total number 2 of array A=[2, 1, 1, 4]. There are 2 ways = (A[0]) and (A[1],A[2]). My code(written in Python) for calculating that 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 ways 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 the algorithm is still dynamic/recursive?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are two issues with your code:

  1. Your code (at some point) makes a recursive call to W(2, 0). Then, it makes a recursive call to W(0, -1). At this point, number is 0, but the index is negative, so 0 rather than 1 is returned, and this possibility is never counted. To resolve this issue, you should return as soon as you realize that 0 can be reached with the current element, rather than making an additional recursive call. (Note that I’m assuming, based on the number < 0 check, that the elements in the array are all strictly positive.)

  2. 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 both of these issues:

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading