Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python Noob to Python: How to code or calculate the minimum # of change?

newbiegirlx

New Coder
Hi, I'm a beginner to python so please bare with me.

Basically I have to write a program that calculates the minimum number of quarters, dimes, nickles, and pennies that I would need to make the change.

For those who are confused I have to mimic this:
To view this content we will need your consent to set third party cookies.
For more detailed information, see our cookies page.

Code:
amount = float(input("Enter amount of change needed: $"))
print("The best way to make", (f"{amount}") , "change in coins is:")
print('\t Quarters:', format(f"{amount}", ">10"))

This is what I've coded so far. I know the third line is horrible.
 
What is horrible about the 3rd line ? It neatly echoes back the amount you typed in. Not very useful though.

Have you not thought about it any further ? How would you do this in real life ? Probably by counting out quarters until the next one would exceed the amount. For the remaining amount (if any), repeat that with dimes, and so on. Write that process down in pseudo code, then translate to Python. If you get stuck with the last step, someone here surely can help out.
 
Python:
quarter = 0.25
dime = 0.10
nickel = 0.05
cent = 0.01

change = 1.66

if( change / quarter > 1 ):
   quarters = int(change/quarter);
   change = change - quarter*quarters;
if( change / dime > 1 ):
   dimes = int(change/dime);
   change = change - dime*dimes;
if( change / nickel > 1 ):
   nickels = int(change/nickel );
   change = change - nickel*nickels;
cents = change;

There are a number of bugs I'll leave up to you.
 
Last edited:
Here is one approach to think about

Python:
def change_maker(money):
    # Create a dict with the change values
    coins = {
        ('quarter', 'quarters'): 0.25,
        ('dime', 'dimes'): 0.10,
        ('nickle', 'nickles'): 0.05,
        ('penny', 'pennies'): 0.01
    }
    # Create a list to hold the change
    moneylist = []
    # Loop through the dict items
    for name, coin in coins.items():
        # Get the how many coins and append to the list
        change = int(money/coin)
        # Append correct if plural or single coin
        moneylist.append(f'{name[0]}: {change}') \
            if change == 1 else moneylist.append(f'{name[1]}: {change}')
        # get the remainder to further calculate coins
        money = round(money%coin,2)
    return f'Change: {", ".join(moneylist)}'
print(change_maker(1.09))

Output
Code:
Change: quarters: 4, dimes: 0, nickle: 1, pennies: 4
 
Last edited:
Here is one approach to think about

Python:
# Dollar amount to change
money = 1.83

# Create a dict with the change values
coins = {
    'quarter': 0.25,
    'dime': 0.10,
    'nickle': 0.05,
    'penny': 0.01
}

# Create a list to hold the change
moneylist = []

# Loop through the dict items
for name, coin in coins.items():
    # Get the how many coins and append to the list
    change = int(money/coin)
    moneylist.append(f'{change} {name}')
    # get the remainder to further calculate coins
    money = round(money%coin,2)

print(f'Change: {", ".join(moneylist)}')

Output
Code:
Change: 7 quarter, 0 dime, 1 nickle, 3 penny
Very elegant solution indeed. The OP is lucky to be handed the complete solution on a plate.
 
I find the two styles interesting.

For my sins, I tend to write "polyglot" code. Code that is mostly the same in all languages.

A python(ic) developer will use all the little implicit or explicit tricks of the language, as.. that's where it's strengths lie.

Both, I think are valid. However, python or not, I expect the basic, non dict based solution will be at least 1 order of magnitude faster.

Does it matter is this example, probably not. Does it happen all the time, that people write "nice" code and later find it doesn't perform and have to make it ugly. Yep.

On performance. What is a millisecond between friends, hey? Well if you have 100,000,000 friends, that single ms adds over a day.
 
One more example using tabulate for printout

Python:
from tabulate import tabulate

coins = {
    'quarters': 0.25,
    'dimes': 0.10,
    'nickles': 0.05,
    'pennies': 0.01
}

def change_maker(money):
    # Create a list to hold the change
    moneylist = []

    # Loop through the dict items
    for name, coin in coins.items():
        # Get the how many coins and append to the list
        change = int(money/coin)

        # Append to list
        moneylist.append(change)

        # get the remainder to further calculate coins
        money = round(money % coin, 2)
    return moneylist

# Get change from function call
data = change_maker(1.32)

# print data out using tabulate
print(tabulate([data], headers=coins.keys(), tablefmt='pretty'))

output

Code:
+----------+-------+---------+---------+
| quarters | dimes | nickles | pennies |
+----------+-------+---------+---------+
|    5     |   0   |    1    |    2    |
+----------+-------+---------+---------+
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom