I'm learning Python(2.7) at the moment, and an exercise says to write a program which counts how many coins you need to pay a specific sum. My solution is this:
sum = input("Bitte gebe einen Euro Betrag ein: ")
coins = []
euro = [20,10,5,2,1,0.5,0.2,0.1,0.05,0.02,0.01]
for i in euro:
while sum >= i:
sum -= i
coins.append(i)
print coins
This is nearly working, but when I input e.g. 17,79 it gives me the coins for 17,78.
Bitte gebe einen Euro Betrag ein: 17.79
[10, 5, 2, 0.5, 0.2, 0.05, 0.02, 0.01]
Why? Has this something to do with round?
Use COUNTIF to figure cells greater than some chosen figure Now COUNTIF function will count the number of cells in the selected data range that contain a numeric value greater than the specified numeric value in criterion expression and will return the result as a number.
just start your count at 1, change your check statement to check if the number is less than 100, and use "count = count + 1" Should work, good luck! Save this answer.
We can use the len( ) function to return the number of elements present in the list.
For currency calculations it's best to avoid float
type if you can, because of accumulating rounding errors. You can do it in a way similar to this:
amount= input("Bitte gib einen Euro Betrag ein: ")
coins = []
cents = [2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1]
amount = int(float(amount) * 100)
for cent in cents:
while amount >= cent:
amount -= cent
coins.append(cent)
print [coin / 100.0 for coin in coins]
I've also changed the variable name from sum
to amount
- sum
will shadow the sum
built-in function.
Result:
Bitte gebe einen Euro Betrag ein: 17.79
[10.0, 5.0, 2.0, 0.5, 0.2, 0.05, 0.02, 0.02]
Alternatively, you can implement this without inner while
loop, like this:
for cent in cents:
n = int(math.floor(amount / cent))
amount -= n * cent
coins += [cent] * n
It's possible to exit loop earlier (if not amount: break
) and avoid unnecessary operations (if not n: continue
), but I omitted these guards for readability.
Another possible alternative is to use the decimal
data type.
It has. If after executing the code you check the 'sum' value, you get something like 0,009999999999999133, which IS smaller than the smallest coin.
My suggestion? Do everything in cents!
sum = int(input("Your text") * 100)
cents = [2000,1000,500,200,100,50,20,10,5,2,1]
coins = []
for i in euro:
while True:
if i <= sum:
coins.append(i)
sum -= i
else:
break
for i in range(len(coins)):
coins[i] /= 100
print(coins)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With