Solution Design First, our makeChange() function should create an empty dictionary in a variable named
change
to store the results to return. Next, we need to determine the amount of each type of coin,
starting with the largest denominations (25-cent quarters) to the smallest (1-cent pennies). This way,
we don’t accidentally use more than the minimum amount of coins by determining we need, for
example, two 5-cent nickels instead of one 10 cent dime.
Let’s start with quarters. Before doing any calculation, if the amount of change to make is less
than 25, then we can skip this calculation entirely since there are zero quarters. Otherwise, if the
amount of change to make is divisible by 25, say the amount parameter is 125, then we can
determine the number of quarters by dividing amount by 25: 125 / 25 evaluates to 5.0.
However, if it isn’t divisible by 25, our result will have a fractional part: 135 / 25 evaluates to
5.4
. We can only add whole numbers of quarters to our change, not 0.4 quarters. Using the //
integer division operator, we can ensure that we only put whole numbers of coins into our change
dictionary: both 125 // 25 and 135 // 25 evaluate to 5.
To deduct the amount of change held by the quarters, we can set change to the amount
remaining after removing 25 cent increments. The word ―remaining‖ hints that we should use the %
modulo operator. For example, if we need to make 135 cents of change and use 5 quarters for 125 of
those cents, we would need to use other coins for the 135 % 25 or 10 remaining cents.
This handles calculating the number of quarters used to make change. We would then copy-paste
this code and make modifications for dimes, nickels, and pennies (in that order). When we finish
processing the number of pennies, the amount parameter will be 0 and the change dictionary will
contain the correct amounts of each coin.