This problem is same as asked in here.
Given a list of coins, their values (c1, c2, c3, … cj, …), and the total sum i. Find the minimum number of coins the sum of which is i (we can use as many coins of one type as we want), or report that it’s not possible to select coins in such a way that they sum up to S.
I”m just introduced to dynamic programming yesterday and I tried to make a code for it.
# Optimal substructure: C[i] = 1 + min_j(C[i-cj])
cdict = {}
def C(i, coins):
if i <= 0:
return 0
if i in cdict:
return cdict[i]
else:
answer = 1 + min([C(i - cj, coins) for cj in coins])
cdict[i] = answer
return answer
Here, C[i] is the optimal solution for amount of money ‘i’. And available coins are {c1, c2, … , cj, …}
for the program, I’ve increased the recursion limit to avoid maximum recursion depth exceeded error. But, this program gives the right answer only someones and when a solution is not possible, it doesn’t indicate that.
What is wrong with my code and how to correct it?
This is a great algorithms question, but to be honest I don’t think your implementation is correct or it could be that I don’t understand the input/output of your function, for that I apologize.
heres a modified version of your implementation.
This is my attempt at solving a similar problem, but this time returning a list of coins. I initially started with a recursive algorithm, which accepts a sum and a list of coins, which may return either a list with the minimun number of coins or None if no such configuration could be found.
ok now lets see if we can improve it, by using dynamic programming (I just call it caching).
now lets run some tests.
granted this tests aren’t robust enough, you can also do this.
its possible that the no such combination of coins equals our random_sum but I believe its rather unlikely …
Im sure there are better implementation out there, I tried to emphasize readability more than performance.
good luck.
Updated
the previous code had a minor bug its suppose to check for min coin not the max, re-wrote the algorithm with pep8 compliance and returns
[]when no combination could be found instead ofNone.