I am trying to make a programme that will return the correct change, in the highest denominations possible
i.e $73 will return 1 x $50, 1 x $20, 1 x $2 and 1 $1
(I am using whole values of $100, $50, $20, $10, $5, $2, $1)
I have a long code that works...it is
hundred = x // 100
hundred_remainder = x % 100
fifty = hundred_remainder // 50
fifty_remainder = hundred_remainder % 50
twenty = fifty_remainder // 20
etc....then
if hundred > 0:
print (str(hundred) + " x $100")
if fifty> 0:
print (str(fifty) + " x $50")
etc....which works fine, but I know there must be a way of writing a function that has a loop to work it out with less typing. Something like X = $345, then it gets 3 x $100, subtracts that from the total and updates X with the remainder, then repeats the process going through each denomination, until complete. I'm just a bit unsure how to figure it out, any guidance will be greatly appreciated!
I think a cool model for this problem is defining the values that you consider "legal" up-front, and then iterating over those from the top to the bottom to reach your counts. Consider the following loop:
#where x is the value from which you're making change
legal = [100,50,20,10,5,2,1,.50,.25,.10,.05,.01]
for dolAmount in legal:
count = x//dolAmount
if count > 0:
print int(count),\
dolAmount,\
" coin(s)" if dolAmount<1 else " dollar bill(s)"
x-=count*dolAmount
# prints lines like this for x=103.58:
#
# 1 100 dollar bill(s)
# 3 1 dollars bill(s)
# 1 0.5 coin(s)
# 1 0.05 coim(s)
# 3 0.01 coin(s)
# ehhh actually it will probably say 2 0.01 coin(s) because floating points....
The formatting needs work (what the heck is a 0.5 coin?), but this is a neat way of saving yourself a lot of code-writing, and the pattern is applicable to other programming endeavors. In general, when you find yourself creating a lot of variables/constants by hand, it's probably time to start thinking about a list (or similar collection)!
Check out http://www.codeskulptor.org/#user39_ur6ybhs9HAmknOL.py for a learning-example of what this would look like in practice (used within a function!) Happy coding!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments