Python function: Find Change from purchase amount

前端 未结 6 788
旧时难觅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:15

    Gee, you mean this isn't problem 2b in every programming course any more? Eh, probably not, they don't seem to teach people how to make change any more either. (Or maybe they do: is this a homework assignment?)

    If you find someone over about 50 and have them make change for you, it works like this. Say you have a check for $3.52 and you hand the cashier a twnty. They'll make change by saying "three fifty-two" then

    • count back three pennies, saying "three, four, five" (3.55)
    • count back 2 nickels, (3.60, 3.65)
    • count back a dime (3.75)
    • a quarter (4 dollars)
    • a dollar bill (five dollars)
    • a $5 bill (ten dollars)
    • a $10 bill (twenty.)

    That's at heart a recursive process: you count back the current denomination until the current amount plus the next denomination comes out even. Then move up to the next denomination.

    You can, of course, do it iteratively, as above.

提交回复
热议问题