python 3.x - How to create function that returns 'change in highest denominations' -


i trying make programme return correct change, in highest denominations possible

i.e $73 return 1 x $50, 1 x $20, 1 x $2 , 1 $1

(i using whole values of $100, $50, $20, $10, $5, $2, $1)

i have long code 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, know there must way of writing function has loop work out less typing. x = $345, gets 3 x $100, subtracts total , updates x remainder, repeats process going through each denomination, until complete. i'm bit unsure how figure out, guidance appreciated!

i think cool model problem defining values consider "legal" up-front, , iterating on top bottom reach counts. consider following loop:

    #where x value you're making change      legal = [100,50,20,10,5,2,1,.50,.25,.10,.05,.01]     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 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 2 0.01 coin(s) because floating points.... 

the formatting needs work (what heck 0.5 coin?), neat way of saving lot of code-writing, , pattern applicable other programming endeavors. in general, when find creating lot of variables/constants hand, it's time start thinking list (or similar collection)!

check out http://www.codeskulptor.org/#user39_ur6ybhs9hamknol.py learning-example of in practice (used within function!) happy coding!


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -