B: Exact Change – Functions Define A Function Called Exact_change That Takes The Total Change Amount In Cents And Calculates The Change Using The Fewest Coins. The Coin Types Are Pennies, Nickels, Dimes, And Quarters. Then Write A Main Program That Reads The Total Change Amount As An Integer Input, Calls Exact_change(), And Outputs The Change, One
The Correct Answer and Explanation is:
:
✅ Correct Python Code:
def exact_change(total_cents):
quarters = total_cents // 25
total_cents %= 25
dimes = total_cents // 10
total_cents %= 10
nickels = total_cents // 5
total_cents %= 5
pennies = total_cents
return quarters, dimes, nickels, pennies
def main():
total_cents = int(input())
if total_cents == 0:
print("no change")
else:
quarters, dimes, nickels, pennies = exact_change(total_cents)
if quarters > 0:
print(f"{quarters} quarter{'s' if quarters > 1 else ''}")
if dimes > 0:
print(f"{dimes} dime{'s' if dimes > 1 else ''}")
if nickels > 0:
print(f"{nickels} nickel{'s' if nickels > 1 else ''}")
if pennies > 0:
print(f"{pennies} penn{'ies' if pennies > 1 else 'y'}")
main()
📝 Explanation
The goal of this program is to convert a total amount of cents (less than a dollar) into the fewest number of coins using only quarters (25¢), dimes (10¢), nickels (5¢), and pennies (1¢). This is a classic greedy algorithm problem, where at each step, we try to use the largest denomination possible to reduce the total amount efficiently.
The exact_change() function takes an integer input total_cents and calculates how many of each coin is needed:
- Quarters: It divides the total amount by 25 to find how many quarters can be used. The remainder is then updated using the modulus operator (
%). - Dimes: It repeats the same logic using 10.
- Nickels: Then for 5.
- Pennies: Whatever is left after dividing by 5 becomes the number of pennies.
The function returns a tuple with counts for each coin.
In the main() function, the program reads user input and checks if the value is zero. If so, it prints “no change.” Otherwise, it calls exact_change() and prints the results. It uses conditionals to skip zero values and handles proper pluralization, like “1 penny” vs. “2 pennies”.
This approach ensures minimal coin use by always selecting the highest-value coin possible at each step, which is optimal for U.S. coin denominations.
