Jump to content
  • Advertisement
Sign in to follow this  
glBender

[Python] How to write this better

This topic is 4090 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Alright, so I've figured out that there is almost always a better way to do things with Python than I'm already doing. Just for practice, I decided to write a function to calculate the correct change(in US coins) to give to a person given a cash amount. This was the simplest way I could figure out to do it, any ideas for improvements?

def calc(amount):
    # pairs the amounts with the names
    types = [(25,'quarters'),(10,'dimes'),(5,'nickels'),(1,'pennies')]
    for t in types:                    #for each kind of coin(greatest to least)
        count = (amount)/t[0]          #how many coins will go into that amount
        if count > 0:                  #if at least one
            print str(count) +' '+t[1] #print out the number
            amount -= count*t[0]       #subtract that amount from the total



Share this post


Link to post
Share on other sites
Advertisement
I really don't like using tuples like that (ie. using hardcoded indices), so one suggestion I have is:


def calc(amount):
# pairs the amounts with the names
types = [(25,'quarters'),(10,'dimes'),(5,'nickels'),(1,'pennies')]
for coinValue, coinName in types: #for each kind of coin(greatest to least)
count = (amount)/coinValue #how many coins will go into that amount
if count > 0: #if at least one
print count, coinName #print out the number
amount -= count*coinValue #subtract that amount from the total




Makes things a lot more explicit :).

EDIT: Don't need str() when printing count, and separating by comma adds in a ' '.

[Edited by - cow_in_the_well on May 7, 2007 2:12:49 AM]

Share this post


Link to post
Share on other sites
Oh okay, I didn't realize I could set up a loop like that... But I guess that makes sense. Thanks for the tips

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!