DEV Community

Tommy
Tommy

Posted on

CS50 Week 6 - Cash in Python (Less Comfortable)

The Problem

The user will input some amount of change and we have to take away the largest posssible coin (¢1, ¢5, ¢10, ¢25) until there is no change left and return how many coins it took to reach 0.

The Solution

Firstly we're going to need the get_float function from cs50.

from cs50 import get_float
Enter fullscreen mode Exit fullscreen mode

Next, we need to make sure the number being input by the user is valid which we will need a variable for. We also need a variable to track how many coins have been used so I decided to declare these first

# Declare variables
change = 0
count = 0
Enter fullscreen mode Exit fullscreen mode

To make sure the input is valid, I used a while loop to check if change is greater than 0. If not, simply re-assign the variable with another prompt. After the input I rounded the value and multiplied by 100.
This makes sure that the input is always possible to work with. If it was 0.00001 for example, multiplying this by 100 would give you 0.001 which is not a possible coin. Rounding it would round to 0 in this case.

# While change is NAN, prompt user
while change <= 0:
    change = get_float("Change owed: ")
    cents = round(change * 100)
Enter fullscreen mode Exit fullscreen mode

Looking back I probably could've put the cents = round(change * 100) after the while loop because it's just making the computer do unnecessary work. Oh well ¯_(ツ)_/¯

All we need to do now is check if cents is greater than the coin values, if it is, take away the value from cents and increment the count.

while cents > 0:
    if cents >= 25:
        cents = cents - 25
        count = count + 1
    elif cents >= 10:
        cents = cents - 10
        count = count + 1
    elif cents >= 5:
        cents = cents - 5
        count = count + 1
    elif cents >= 1:
        cents = cents - 1
        count = count + 1
Enter fullscreen mode Exit fullscreen mode

I'm 99% sure the order is important here. We want to check if the largest coin is possible FIRST before checking the others.

Once this is done we can simply print the number of coins!

print(count)
Enter fullscreen mode Exit fullscreen mode

Full code:

from cs50 import get_float

# Declare variables
change = 0
count = 0

# While change is NAN, prompt user
while change <= 0:
    change = get_float("Change owed: ")
    cents = round(change * 100)

# While cents is greater than 0, take away largest coin possible  and increment count
while cents > 0:
    if cents >= 25:
        cents = cents - 25
        count = count + 1
    elif cents >= 10:
        cents = cents - 10
        count = count + 1
    elif cents >= 5:
        cents = cents - 5
        count = count + 1
    elif cents >= 1:
        cents = cents - 1
        count = count + 1

print(count)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)