Sign in to follow this  
glBender

[Python] How to write this better

Recommended Posts

glBender    156
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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this