Convert cents to quarters, nickels, dimes and pennies using Python - python

I'm using Python, and I am trying to convert a certain amount of money in cents to its equivalent in quarters, nickels, dimes and pennies.
This is what I have so far, but I see the problem is that I don't know how to take the remainder from the quarters and break it down into dimes, nickels and pennies. I'm new to this and just having a hard time. I'm not asking for someone to solve the problem, just point out what I did wrong (and maybe what I need to do to fix it).
# Convert some money to an appropriate collection of cents
penny = 1
nickel = 5
dime = 10
quarter = 25
quarters = 0
dimes = 0
nickels = 0
pennys = 0
cents = int(input("Please enter an amount of money you have in cents: "))
if cents >= 25:
quarters = cents / quarter
cents % quarter
if cents >= 10:
dimes = cents/dime
cents % dime
if cents >= 5:
nickels = cents /nickel
cents % nickel
if cents > 0:
pennys = cents / penny
cents = 0
print ("The coins are: quarters", quarters,\
",dimes", dimes, ",nickels", nickels, ", and pennys.", pennys)

Using divmod, it's just three lines:
quarters, cents = divmod(cents, 25)
dimes, cents = divmod(cents, 10)
nickels, pennies = divmod(cents, 5)

There are two operations that you need here: integer division and modulo.
Integer division A / B asks a simple question: How many times will B fit into A cleanly (without having to break B into decimal pieces)? 2 fits into 8 cleanly 4 times. 2 fits into 9 cleanly 4 times as well.
Modulo A % B asks the same question but gives the flip-side of the answer: Given that A goes into B cleanly some number of times, what's left over? 2 goes into 8 cleanly 4 times with nothing left over, so 2 % 8 is 0. 2 goes into 9 cleanly 4 times but 1 is left over, so 2 % 9 is 1.
I'll give you another example, and let you make the transition from that to your problem. Let's say I'm given a number of seconds, and I need to convert it to days, hours, minutes and seconds.
total_seconds = 345169
# Specify conversion between seconds and minutes, hours and days
seconds_per_minute = 60
seconds_per_hour = 3600 # (60 * 60)
seconds_per_day = 86400 # (3600 * 24)
# First, we pull out the day-sized chunks of seconds from the total
# number of seconds
days = total_seconds / seconds_per_day
# days = total_seconds // seconds_per_day # Python3
# Then we use the modulo (or remainder) operation to get the number of
# seconds left over after removing the day-sized chunks
seconds_left_over = total_seconds % seconds_per_day
# Next we pull out the hour-sized chunks of seconds from the number of
# seconds left over from removing the day-sized chunks
hours = seconds_left_over / seconds_per_hour
# hours = seconds // seconds_per_hour # Python3
# Use modulo to find out how many seconds are left after pulling out
# hours
seconds_left_over = seconds_left_over % seconds_per_hour
# Pull out the minute-sized chunks
minutes = seconds_left_over / seconds_per_minute
# minutes = seconds_left_over // seconds_per_minute # Python3
# Find out how many seconds are left
seconds_left_over = seconds_left_over % seconds_per_minute
# Because we've removed all the days, hours and minutes, all we have
# left over are seconds
seconds = seconds_left_over

Was struggling with this yesterday evening. True, you need division and modulo. Not the most Pythonic way, but it works for any amount, when you restrict the amount of dollars you can input into the vending machine to $5.00. This question has been asked around and has been continually ignored. Maybe because it is homeworksque... Anyway....
def vending_machine_change():
cost = float(input("Enter cost of item: "))
change= 5.00-cost
dollars = int(change)
quarters_change= float("%.2f" % ((change-dollars)))
quarters =int(quarters_change/0.25)
dime_change= float("%.2f" % (quarters_change%0.25))
dimes=int(dime_change/0.10)
nickel_change = float("%.2f" % (dime_change%0.10))
nickels= int(nickel_change/0.05)
pennys = int(nickel_change*100)
print("Change amount: " + str((dollars)) + ' Dollars, ' + str((quarters)) + ' Quarters, '+ str((dimes)) + ' Dimes, '+ str((nickels)) + ' Nickels, '+ str((pennys)) + ' Pennies' )
pass

Related

How can I implement the current algorithm into a for loop in increments?

I need the loop to follow the algorithm of the code below. Every loop should take the first day (2) and add the average (.3) to it.
startOrganism = 2
startOrganism = int(input("Starting number of organisms:"))
dailyInc = .3
dailyInc = float(input("Average daily increase (percent): "))
numberDaysMulti = 10
numberDaysMulti = int(input("Number of days to multiply: "))
for x in range(numberDaysMulti):
(Needs to be below)
Day 1 2
Day 2 2.6
Day 3 3.38
etc.
Ok, I've assumed that the user will input the percent daily increase as 0.3 as opposed to 30:
startOrganism = int(input("Starting number of organisms:"))
dailyInc = float(input("Average daily increase (percent): "))
numberDaysMulti = int(input("Number of days to multiply: "))
percDailyInc = 1 + dailyInc
for day in range(numberDaysMulti):
print(f'Day {day+1} {startOrganism:.2f}')
startOrganism *= percDailyInc
Sample Output:
Day 1 2.00
Day 2 2.60
Day 3 3.38
Day 4 4.39
Day 5 5.71
Day 6 7.43
Day 7 9.65
Day 8 12.55
Day 9 16.31
Day 10 21.21
This sort of computation can be handled mathematically, using the following formula:
organisms = starting_organisms * ((1.0 + growth_rate) ^ days)
Where the growth_rate is the percent increase per unit of time, in your case days. Then it becomes a matter of simply printing out the value for each day.
starting_organisms = int(input("Starting number of organisms:"))
growth_rate = float(input("Average daily increase in percent): ")) # 0.3 = 30%
period = int(input("Number of days to grow:"))
growth = [(starting_organisms * ((1.0 + growth_rate) ** day) for day in range(period)]
# The list 'growth' has all our values, now we just print them out:
for day, population in enumerate(growth):
print(f"Day {day} {population}")
(This uses a zero-index for the days. That is, 'day 0' will be your starting number. Indexing this way saves you off-by-one errors, but you can change the print statement to be {day + 1} to hide this data structuring from the user.)
There is an alternative method where you carry state in each loop, calculating the next day as you iterate. However, I'd recommend separating the concern of calculation and display - that instinct will serve you well going forward.
The growth = [... for day in range(period)] is a list comprehension, which works much like a one-line for-loop.
startOrganism = 0
startOrganism = int(input("Starting number of organisms:"))
dailyInc = 0
dailyInc = float(input("Average daily increase (percent): "))
dayApproximate = 0
numberDaysMulti = 0
numberDaysMulti = int(input("Number of days to multiply: "))
for x in range(numberDaysMulti):
startOrganism = dailyInc * startOrganism + startOrganism
print(startOrganism)

Calculate change from paid amount

Why is this code creating an infinite loop? I would think this should be an appropriate solution for this type of problem. For example, if the price was $5 and you paid $5.47, the program would print:
Quarters: 1
Dimes: 2
Nickels: 0
Pennies: 2
However, an infinite loop occurs and I'm not sure why. Anyone know the reason?
price = round(float(input("Enter the price: ")), 2)
print price
paid = round(float(input("Enter the amount paid: ")), 2)
print paid
change = round(float(paid - price), 2)
print change
quarters = 0
dimes = 0
nickels = 0
pennies = 0
while change > 0.00:
print change
if change >= .25:
change = change - .25
quarters += 1
continue
elif change >= .1:
change = change - .1
dimes += 1
continue
elif change >= .05:
change = change - .05
nickels += 1
elif change >= .01:
change = change - .01
pennies += 1
print "Quarters: " + str(quarters)
print "Dimes: " + str(dimes)
print "Nickels: " + str(nickels)
print "Pennies: " + str(pennies)
Rather than dealing with loops, I would suggest just subtracing off the change that you already gathered, prioritizing larger coins.
price = float(input("Enter the price: "))
paid = float(input("Enter the amount paid: "))
change = paid - price
if change < 0:
raise ValueError('Not enough paid')
quarters = change // 0.25
dimes = (change - (0.25 * quarters)) // 0.10
nickels = (change - (0.25 * quarters) - (0.10 * dimes)) // 0.05
pennies = 100 * (change - (0.25 * quarters) - (0.10 * dimes) - (0.05 * nickels))
print("Quarters: {:.0f}".format(quarters))
print("Dimes: {:.0f}".format(dimes))
print("Nickels: {:.0f}".format(nickels))
print("Pennies: {:.0f}".format(pennies))
There's one minor bug in the code which causes the program to only work correctly if price and amount paid are interchanged (e.g. price = 2, paid = 1). But that is not the issue causing the infinite loop.
Your code creates an infinite loop for e.g. the following arguments:
price: 5.6
paid: 5.4
The reason for the infinite loop can be seen from your own print output:
0.009999999999999275
0.009999999999999275
0.009999999999999275
0.009999999999999275
0.009999999999999275
0.009999999999999275
0.009999999999999275
...
Since change < 0.01, no if clause applies and thus the loop is never left.
How could you solve the problem more robustly?
Here's a sketch
from math import floor
change = paid - price
quarters = int(floor(change / 0.25))
change -= quarters * 0.25
dimes = int(floor(change / 0.1))
change -= dimes * 0.1
nickels = int(floor(change / 0.05))
change -= nickels * 0.05
pennies = int(floor(change / 0.01))
change -= pennies * 0.01
remaining = change
print("Quarters:", quarters)
print("Dimes:", dimes)
print("Nickels:", nickels)
print("Pennies:", pennies)
Personally I would also condense this into a loop over the coin type:
increments = {"quarter":0.25, "dimes": 0.1, "nickels": 0.05, "pennies": 0.01}
change_parts = {}
for inc_name, inc in increments.items():
amount = int(floor(change / inc))
print(inc_name, inc, amount)
change -= amount * inc
change_parts[inc_name] = amount
for inc_name, amount in change_parts.items():
print(inc_name + ":", amount)

Mixing keyword and default arguments in python 3.5.1

I'm a newbie and taking an online python class through an online workbook. I can't seem to figure out how to get the output to display like the example shown:
Problem instructions:
Write a function number_of_pennies() that returns the total number of pennies given a number of dollars and (optionally) a number of pennies. Ex: 5 dollars and 6 pennies returns 506.
Here is what I have:
def number_of_pennies(dollars = (),pennies=())
return number_of_pennies
print(number_of_pennies(5, 6)) # Should print 506
print(number_of_pennies(4)) # Should print 400
Thanks to your help I just changed it to this:
def number_of_pennies(dollars = 0,pennies=0):
number_of_pennies= (dollars * 100) + pennies
return number_of_pennies
print(number_of_pennies(5, 6)) # Should print 506
print(number_of_pennies(4)) # Should print 400
Default arguments are used when the caller doesn't supply a value. So, what should be the default? In your case, if the user doesn't supply dollars, zero dollars seems like a reasonable choice. Same with pennies. Since number_of_pennies(4) should be 400 you know that they want dollars to be the first parameter. The remainder is just the math.
number_of_pennies is just the name of the function which would be an odd thing to return. In fact, when you try it you get something like <function number_of_pennies at 0x7ff4e962d488> which means that the function returned its own function object. Instead return the data you calculate... that's much more useful!
>>> def number_of_pennies(dollars=0, pennies=0):
... return dollars * 100 + pennies
...
>>> print(number_of_pennies(5,6))
506
>>> print(number_of_pennies(4))
400
def number_of_pennies(dollars = 0, pennies = 0):
return dollars * 100 + pennies
print(number_of_pennies(int(input()), int(input()))) # Both dollars and pennies
print(number_of_pennies(int(input()))) # Dollars only
def number_of_pennies(n,x=0):
return n*100+x
I did the same workbork. This is what I came up with:
def number_of_pennies(dollars=0, pennies=0):
dollars = dollars * 100
pennies = pennies
total = dollars + pennies
return total
print(number_of_pennies(int(input()), int(input()))) # Both dollars and pennies
print(number_of_pennies(int(input()))) # Dollars only

Python-Modulus-Stuck with a coin-for-given-dollar-amount scenario

Specs: Ubuntu 13.04, Python 3.3.1
General Background: total beginner to Python;
Question-specific background: I'm exhausted trying to solve this problem, and I'm aware that, besides its instructional value for learning Python, this problem is boring and does not in any way make this world a better place :-( So I'd be even more grateful if you could share some guidance on this exhausting problem. But really don't want to waste your time if you are not interested in this kind of problems.
What I intended to do: "Calculate the number of basic American coins given a value less than 1 dollar. A penny is worth 1 cent, a nickel is worth 5 cents, a dime is worth 10 cents,
and a quarter is worth 25 cents. It takes 100 cents to make 1 dollar. So given an amount less than 1 dollar (if using floats, convert to integers for this exercise), calculate the number of each type of coin necessary to achieve the amount, maximizing the number of larger denomination coins. For example, given $0.76, or 76 cents, the correct output would be "3 quarters and 1 penny." Output such as "76 pennies" and "2 quarters, 2 dimes, 1 nickel, and 1 penny" are not acceptable."
What I was able to come up with:
penny = 1
nickel = 5
dime = 10
quarter = 25
i = input("Please enter an amount no more than 1 dollar(in cents): ")
i = int(i)
if i > 100:
print ("Please enter an amount equal or less than 100. ")
elif i >= quarter:
quarter_n = i % quarter
i = i - quarter * quarter_n
if i >= dime:
dime_n = i % dime
i = i - dime * dime_n
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",dime_n,"dimes",nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",dime_n,"dimes",penny_n,"pennies")
else:
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",penny_n,"pennies")
else:
if i >= dime:
dime_n = i % dime
i = i - dime * dime_n
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (dime_n,"dimes",nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (dime_n,"dimes",penny_n,"pennies")
else:
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (penny_n,"pennies")
This solution, though the best I could come up with, does not work as expected when fed with actual input numbers. And I'm unable to figure out why. Besides, I know that even from sheer size of the code that something is wrong. I searched for similar questions but the closest I got was one that dealt with very difficult math which I couldn't understand.
My question: I know I can't ask for a complete solution because that's down to me to figure it out. I'll appreciate either a) general pointer on the correct line of thinking b) critiques to my current code/line of thinking so that I might be able to improve it.
Thank you for taking the time, even just reading this!
I think your solution may actually be working if you do a "find and replace" for all the mod operators %, switching in integer division //.
Say you have 76 cents and want to find the number of quarters. Using 76 % 25 results in 1 whereas 76 // 25 is 3.
With regard to the code, you should probably be thinking in terms of iterating over the possible coin values rather than a huge if, elif mess.
Try something like this. The only part that may need some explaining is using divmod but its really just a tuple of the integer division, modulo result. You can use that to get the number of coins and the new amount, respectively.
def coins_given(amount):
coins = [(25, 'quarter'), (10, 'dime'), (5, 'nickel'), (1, 'penny')]
answer = {}
for coin_value, coin_name in coins:
if amount >= coin_value:
number_coin, amount = divmod(amount, coin_value)
answer[coin_name] = number_coin
return answer
print coins_given(76)
# {'quarter': 3, 'penny': 1}
i think your algorithm is too complicated,
you don't need all the elifs and the elses
just check with and if and then modidy the remaining amount until you get to zero
something like this
penny = 1
nickel = 5
dime = 10
quarter = 25
q = 0
d = 0
n = 0
p = 0
i = input("Please enter an amount no more than 1 dollar(in cents): ")
i = int(i)
if i>=25:
q = i/quarter
i %= quarter
if i>=10:
d = i/dime
i%=dime
if i>=5:
n = i/nickel
i %= nickel
if i>0:
p = i/penny
i = 0
print "The coins are %i quarters, %i dimes, %i nickels and %i pennys." %(q , d, n, p)
>>>
Please enter an amount no more than 1 dollar(in cents): 99
The coins are 3 quarters, 2 dimes, 0 nickels and 4 pennys.
>>>
Please enter an amount no more than 1 dollar(in cents): 76
The coins are 3 quarters, 0 dimes, 0 nickels and 1 pennys.
dime=10
nickel=5
penny=1
quarter=25
def change(cents):
changeIs = ""
qs = cents/quarter
cents %= quarter
if qs > 0 :
changeIs += str(qs) + " quarter(s)"
ds = cents/dime
cents %= dime
if ds > 0 :
changeIs += " " + str(ds) + " dime(s)"
ns = cents/nickel
cents %= nickel
if ns > 0 :
changeIs += " " + str(ns) + " nickel(s)"
if cents > 0 :
changeIs += " " + str(cents) + " cent(s)"
return changeIs
if __name__ == '__main__':
cents=int(raw_input("Enter the change: "))
print change(cents)

Rounding up with pennies in Python?

I am making a change program in python. The user must input a dollar amount and then the program will calculate the change in twenties, tens, fives, ones, quarters, dimes, nickels, and pennies. I was instructed to use the round function for the pennies because If I input an amount of $58.79, the program tells me to give 3 pennies back when it should be 4. Is there a way to round up these pennies?
I know the value of a penny is .01, but python reads this as .100000000001 which I believe is the problem.
Any help is appreciated, here is the section I need rounded:
# get the amount to change from the user
change = input("Please enter the amount to change: $")
print "To make change for $",change,"give the customer back:"
# calculate number of twenties
twenties = int(change/ 20)
print twenties, "twenties"
change = change - twenties *20
# calculate tens
tens = int(change / 10)
print tens, "tens"
change = change - tens *10
#calculate fives
fives = int(change / 5)
print fives, "fives"
change = change - fives *5
#calculate ones
ones = int(change / 1)
print ones, "ones"
change = change - ones * 1
#calculate quarters
quarters = int(change / .25)
print quarters, "quarters"
change = change - quarters * .25
#calculate dimes
dimes = int(change / .10)
print dimes, "dimes"
change = change - dimes * .10
#calculate nickels
nickels = int(change / .05)
print nickels, "nickels"
change = change - nickels * .05
#calculate pennies
pennies = int(change / .01)
print pennies, "pennies"
Multiply the user's inputed dollar value by 100, convert to int, and work in units of pennies.
Integer arithmetic is dead simple (and exact). Floating point arithmetic is tricky and forces you to use more brain cells :) . Save brain cells and work entirely in ints.
The problem is that 0.01 cannot be accurately represented as a binary floating point value (which is how normal floats are stored – this is true for any language, not just Python). So if you need exact values for dollars and cents, you can use the decimal module. That way you can be sure that your values will be rounded exactly.
Or (since Decimals might be overkill here), first multiply every dollar value by 100 (this is not the same as dividing by 0.01 for the above reasons!), convert to int, do your calculations, and divide by 100.
The problems you are having are a result of imprecise floating-point arithmetic. There is no way to precisely represent 0.01 in IEEE floating point. That is one reason not to use floats when working with currency.
You should use decimals or even integers, because you know there are at most 2 digits after the decimal point. In that case, just work with the amount in pennies.
On the problem itself, I think the easiest way to do it is convert your amount in dollars to the amount in pennies, then iterate through a predefined list of values containing listing the equivalent amount of pennies (in descending order) for each denomination:
def change(amount):
# this can be removed if you pass the amount in pennies
# rather than dollars
amount = int(round(amount*100))
values = [2000, 1000, 500, 100, 25, 10, 5, 1]
denom = ['twenties', 'tens', 'fives', 'ones', 'quarters', 'dimes', 'nickels', 'pennies']
for i in range(len(values)):
num = amount / values[i]
amount -= num * values[i]
print str(num) + " " + denom[i]
Now calling change(58.79) will print
2 twenties
1 tens
1 fives
3 ones
3 quarters
0 dimes
0 nickels
4 pennies
As seen on codepad.org
use the decimal package
http://docs.python.org/library/decimal.html
it is meant exactly for this kind of use case
>>> from math import ceil
>>> a = 58.79
>>> ceil(a % 0.05 * 100)
4.0
>>>
[edit]
Now that I think of it, might aswell just go with
>>> a = 58.79
>>> a*100 % 5
4.0

Categories

Resources