0
def get_money(money):
 
    lst_banknotes = {1000: 0,
                     500: 0,
                     200: 0,
                     100: 0,
                     50: 2,
                     20: 10,
                     10: 10}
    summa = 0
    res = []
    for k, v in sorted(lst_banknotes.items(), key=lambda x: -x[0]):
        while summa + k <= money and lst_banknotes[k] > 0:
            summa += k
            lst_banknotes[k] -= 1
            res.append(k)
 
    return res
 
print(get_money(1600))

How to set the function to display the correct banknotes? If the entire amount cannot be withdrawn the function ceases to work

not_speshal
  • 22,093
  • 2
  • 15
  • 30

1 Answers1

1

raise exceptions when there is insufficient money or when you can't return the exact amount:

def get_money(money):
    
    lst_banknotes = {1000: 0, 500: 0, 200: 0, 100: 0, 50: 2, 20: 10, 10: 10}
    available = sum(k*v for k,v in lst_banknotes.items())
    if money > available:
        raise ValueError(f"Total amount available is {available}")
    
    result = list()
    remaining = money
    for k, v in lst_banknotes.items():
        if v == 0:
            continue
        q = remaining//k
        notes = min(q, v)
        
        result += [k]*notes
        remaining -= k*notes
    
    if sum(result) != money:
        raise ValueError("Unable to fetch exact amount.")
    return result
Output:
>>> get_money(350)
[50, 50, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 10, 10, 10, 10, 10]

>>> get_money(205)
ValueError: Unable to fetch exact amount.

>>> get_money(500)
ValueError: Total amount available is 400
not_speshal
  • 22,093
  • 2
  • 15
  • 30