JAM
JAM

Reputation: 131

Change Calculation in Python

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)

Upvotes: 0

Views: 838

Answers (2)

Ken T
Ken T

Reputation: 2553

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]]

Upvotes: 2

Roman
Roman

Reputation: 9441

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")

Upvotes: 1

Related Questions