I'm calculating the minimum coinage of change in Python using the following code:
def change(am):
totalcoins = []
for coin in dstock:
while coin[0] <= am and coin[1] > 0:
totalcoins.append(coin[0])
am = round(am - coin[0], 2)
coin[1] = coin[1] - 1
return totalcoins
dstock is a variable created from a CSV file. Here is the print of dstock:
[[1.0, 100], [0.5, 100], [0.2, 100], [0.1, 100], [0.05, 100], [0.02, 100], [0.01, 100]]
Explained: [denomination,stock level] -- at present there are 100 of each.
I have figured how to update the stock level and how to calculate the change but I can't figure out how to produce an error if there is not enough stock to produce the change.
example:
Stock = [[1.0, 0], [0.5, 0], [0.2, 0], [0.1, 0], [0.05, 0], [0.02, 0], [0.01, 2]]
change = 0.03
if stock < change print(error: not enough stock to produce change)
2 Answers 2
No additional loop.
Edited to accommodate the update of stock is only allowed if there is enough change.
def change(am, dstock):
totalcoins = []
hstock=dstock[:] #make a copy of dstock
for coin in hstock:
while coin[0] <= am and coin[1] > 0:
totalcoins.append(coin[0])
am = round(am - coin[0], 2)
coin[1] = coin[1] - 1
if am>0:
raise ValueError("not enough stock to produce change")
else:
dstock = hstock
return totalcoins
dstock = [[1.0, 0], [0.5, 0], [0.2, 0], [0.1, 0], [0.05, 0], [0.02, 0], [0.01, 3]]
print change(0.03, dstock) #[0.01, 0.01, 0.01]
print dstock #[[1.0, 0], [0.5, 0], [0.2, 0], [0.1, 0], [0.05, 0], [0.02, 0], [0.01, 0]]
2 Comments
Your question is quite ambiguous, but I take it that you are asking how to produce an error. If not, please elaborate
Use an exception and a conditional:
if stock < stock_required_for_change:
raise Exception("Not enough Stock to produce change")
sum(a*b for (a,b) in Stock)a*b for (a, b) in Stockwill multiply the sublists together (1.0 * 0, 0.01 * 2, etc) andsumwill take those values and add them together.change. If you really need to throw an error, then you should implement exception otherwise you can just check two numbers and print message if condition is not met