Search code examples
pythoncomputer-sciencecs50

CS50 pset6 // cash.py // Not Showing The Proper amount of coins needed


I have been trying to fix this issue but in the task, for pset6 it says that you need to test the code you wrote with some values it works for some of them but for the rest, it doesn't work I am not sure why.

so the image below is the values that I need to try the code I wrote works for the first 3 inputs but after 0.15 the values like 1.60, 23, and 4.2 does not work I am not sure why

from cs50 import get_float

coin_count =0
change = get_float("Enter Change Amount: ")
total_amount = round(change * 100);
coin_amounts = [25,10,5,1]

while change<=0:
    change = get_float("Enter Change Amount: ")

while total_amount > 0:
    for i in coin_amounts:
        if total_amount >=i:
            total_amount  -= i
            coin_count+=1

print(str(coin_count) + " coins");

Solution

  • Work through the logic.

    Lets say you start with 1.6 (160).

    160 > 25 so remove 25

    135 > 10 so remove 10

    125 > 5 so remove 5

    120 > 1 so remove 1

    119 > 25 so remove 25

    See the problem ?

    When you get into bigger numbers having removed 10 then 5 then 25 then 10 again means you go off the rails - those [10 10 5] could be a single 25. You need to remove as many 25s as you can before removing all the 10s that you can then all the 5s and what is left has to be 1s.