2

Given a list of coins and a positive integer n>0 I need to find the number of permutations which sum up to n. Each coin on the list can be used many times. for example - given the following list: lst = [1,3,4] and n=4, the function should return 4: for : [1,1,1,1], [1,3], [3,1] and [4]. I was asked to give a reursive solution. I know how to write a recursive code which counts the number of combinations, but I don't know how to write the code which counts the number of permutations.

This is my code:

def coin_change(lst, n):
if n == 0:
    return 1
if len(lst) == 0:
    return 0
if n<0:
    return 0

return coin_change(lst, n-lst[0]) + coin_change(lst[1:], n)

Thanks

user429400
  • 3,145
  • 12
  • 49
  • 68
  • 1
    Can you show what you have for finding the combinations? That might be a good starting point for the permutations problem. – Blckknght Jul 13 '21 at 22:04
  • There have been quite a lot of similar questions. Some code that you wrote will already help. However a very naive approach would be to generate every possible permutation and then filter out those who do not match n when you return your recursion. – Tom-Oliver Heidel Jul 13 '21 at 22:07
  • @Blckknght : I've added my code to the post – user429400 Jul 13 '21 at 22:17

1 Answers1

2

You have some issues. You keep trying to reduce the list, but because repeats are allowed, you can't do that. You have to try the whole list every time, until the sum exceeds the count. This does what you ask:

track = []
def coin_change(lst, n, sofar=[]):
    if sum(sofar) == n:
        print("winner", sofar)
        track.append( sofar )
        return
    if sum(sofar) > n:
        return
    for i in lst:
        coin_change( lst, n, sofar+[i] )
    return track

print(coin_change([1,3,4], 4))

Output:

winner [1, 1, 1, 1]
winner [1, 3]
winner [3, 1]
winner [4]
[[1, 1, 1, 1], [1, 3], [3, 1], [4]]

An alternate approach would use yield to generate the winners and yield from to pass through winners from the inner calls.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • thanks! so basically when you count permutations rather than combinations you cannot avoid loops? – user429400 Jul 13 '21 at 22:31
  • Well, this is really "combinations with replacement", right? There's really no way to avoid a loop here, because you have to try every option at every step. – Tim Roberts Jul 13 '21 at 22:33