Python function: Find Change from purchase amount

前端 未结 6 780
旧时难觅i
旧时难觅i 2021-01-29 13:56

I\'m looking for the most efficient way to figure out a change amount (Quarters, dimes, nickels, and pennies) from a purchase amount. The purchase amount must be less than $1, a

6条回答
  •  离开以前
    2021-01-29 14:32

    Your best bet is to probably have a sorted dictionary of coin sizes, and then loop through them checking if your change is greater than the value, add that coin and subtract the value, otherwise move along to the next row in the dictionary.

    Eg

    Coins = [50, 25, 10, 5, 2, 1]
    ChangeDue = 87
    CoinsReturned = []
    For I in coins:
       While I >= ChangeDue:
            CoinsReturned.add(I)
            ChangeDue = ChangeDue - I
    

    Forgive my lousy python syntax there. Hope that's enough to go on.

提交回复
热议问题