Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: change calculator

Tags:

python

I am trying to calculate the number of quarters, dimes and nickles needed to sum to an amount of change with the least coins possible. Here is my code:

x = raw_input("Please enter an amount of change")
x = float(x)
q = .25
d = .1
n = .05
numberQ = x/q
numberQ = int(numberQ)
money2 = x - (numberQ * q)
numberD = money2/d
numberD = int(numberD)
money3 = money2 - (numberD * d)
numberN = money3/n
numberN = int(numberN)
print numberQ
print numberD
print numberN

The output is off. For example, if I enter 1.95 it will return 7 quarters, 1 dime and 1 nickel when it should be 7 quarters 2 dimes and 0 nickels.

like image 265
Thomas Stirling Avatar asked Nov 30 '25 02:11

Thomas Stirling


2 Answers

The problem is in the second step. If you start with 1.95, step one returns 7 quarters with a remainder of $0.20. So money2 is now 0.20. Now we divide by the value of a dime. Because of floating point error our result is likely not an even 2 but more like 1.9999999. Python 2.7's int() method rounds towards zero so this gets rounded to 1 dime. The remainder is $0.10 and this gets divided by the value of a nickle which leads to the same problem but this time it rounds down to one nickle.

To fix this, I recommend using an integer number of pennies instead of a floating point value representing dollars.

So, 1.95 becomes 195 and the values of a quarter, a dime, and a nickle are 25, 10, and 5, respectively.

Edit Try this:

x = raw_input("Please enter an amount of change (in pennies)")
x = int(x)
q = 25
d = 10
n = 5
numberQ = (x - (x % q))/q
money2 = x % q
numberD = (money2 - (money2 % d))/d
money3 = money2 % d
numberN = (money3 - (money3 % n))/n
pennies = money3 % n
print numberQ
print numberD
print numberN
print pennies

The % gives the remainder of an integer division. If we subtract the remainder from the amount we started with and divide that by the coin value we know the result will be a whole integer. The remainder becomes the new amount of money.

like image 175
wrkyle Avatar answered Dec 02 '25 17:12

wrkyle


It is due to float not precisely holding the values.

>>> money2/d
1.9999999999999996

Try multiplying everything by 100:

x = float(195)
q = float(25)
d = float(10)
n = float(5)
numberQ = x/q
numberQ = int(numberQ)
money2 = x - (numberQ * q)
numberD = money2/d
numberD = int(numberD)
money3 = money2 - (numberD * d)
numberN = money3/n
numberN = int(numberN)
print numberQ
print numberD
print numberN

Online Example

Edit: You could also use the decimal package to do this:

from decimal import Decimal
x = Decimal('1.95')
q = Decimal('.25')
d = Decimal('.10')
n = Decimal('.05')
numberQ = x/q
numberQ = int(numberQ)
money2 = x - (numberQ * q)
numberD = money2/d
numberD = int(numberD)
money3 = money2 - (numberD * d)
numberN = money3/n
numberN = int(numberN)
print numberQ
print numberD
print numberN
like image 20
Jeff Avatar answered Dec 02 '25 16:12

Jeff