0

i need to write an algorithm that receives a number and a list of numbers and returns the number of possible combinations of numbers from the list that can create the sum number. for example: def coin(5,[1,2,5,6] should return the number 4 because there are 4 possible combinations from the list that can create together the number 5. below there is the code that i tried but it does not work. the output is 6 instead of 4 and i would love some help in understanding why.

def coin(n,lst):
    if n<=1:
        return 1
    else:
        total=0
        for i in range(len(lst)):
            change=lst[i]
            if change>n:
                continue
            else:
                result=coin(n-change,lst[i:])
                if result>0:
                    total+=result
        return total
print(coin(5,[1,2,5,6]))
Wenfang Du
  • 8,804
  • 9
  • 59
  • 90
ofek reches
  • 1
  • 1
  • 1

2 Answers2

1

The mistake is in the base case:

    if n<=1:
        return 1

This is only valid if 1 is one of the allowed coins. But in your recursive case, you slice the list at lst[i:], so not all coins will be allowed every time. Sometimes, 1 isn't one of the allowed coins, in which case there are zero ways to make a total of 1, not one way. To fix it, write something like:

    if n <= 1:
        if n == 0 or n in lst:
            return 1
        else:
            return 0

This is correct because you can make change for n in the base case either if n is 0 (we can always make 0), or if n is 1 and 1 is one of the allowed coins.

That said, it would be simpler to let the recursive case handle 1, so the base case only needs to handle 0; this is also correct:

    if n == 0:
        return 1
kaya3
  • 47,440
  • 4
  • 68
  • 97
-1
int coinCount( int C[], int m, int n )

    {
        // if n is 0 return 1
        if (n == 0)
        return 1;

        // If n is less than 0 then no solution exists
        if (n < 0)
        return 0;

        // If there are no coins and n is greater than 0, then no solution exists
        if (m <=0 && n > 0)
        return 0;

        return coinCount( C, m - 1, n ) + coinCount( C, m, n-C[m-1] );
    }
torap
  • 656
  • 6
  • 15