0

I have an assignment to make a function that receives only an integer and a list of integers(can't add anything else). It should return the number of combinations from the list that sums to k, the order doesn't matter(The coin change problem). Also, I need to use recursion. Here's what I did:

def coin(k, lst):
    if k == 0:
        return 1
    if k < 0:
        return 0
    else:
        sum = 0
        for i in range(len(lst)):
            sum += coin(k - lst[i], lst)
        return sum

The problem is it sums same combination multiple times. For example,

coin(5, [1, 2, 5, 6])

returns 9.

It should return 4 (11111, 122, 1112, 5).

Help
  • 25
  • 3

1 Answers1

0

Your code is actually missing required parameters, also you are using a for loop with recursion that's what messing up with the essence of recursion. Try using this code:

def coin(k, lst, n):
    if(k == 0):
        return 1
    elif(n==0 or k<0):
        return 0
    else:
        return coin(k, lst, n-1) + coin(k-lst[n-1], lst, n)
arr = [1, 2, 5, 6]
n = len(arr)
print(coin(5, arr, n))

In the else part: The first recursive call is leaving the current array element behind and calling the remaining array. The Second recursive call is subtracting the current array element from the required change(k) and recalling again with the current element so as to choose it again in future calls.

Also, the addition between the first and second call indicates that we want all the possible combinations, that can either be derived from first recursive call or second recursive call

  • Thank you! but the function has to be coin(k, lst). I can't add n = len(lst). Do you have any idea for how to write the line: coin(k, lst, n-1) + coin(k-lst[n-1], lst, n) without it? – Help Apr 24 '21 at 16:36
  • @Help You can write another function and call it from inside the coin() function, in that way you can use arguments in whatever way possible. – Anurag Srivastava Apr 24 '21 at 16:49