0

So I'm working on a school project with the following prompt:

Write a program with total change amount as an integer input, and output the change using the fewest coins, one coin type per line. The coin types are Dollars, Quarters, Dimes, Nickels, and Pennies. Use singular and plural coin names as appropriate, like 1 Penny vs. 2 Pennies.

Ex: If the input is:

45

The output is:

1 Quarter
2 Dimes

I've traveling down a rabbit hole trying to get this to work. I have the math right for the computation part, but then I decided to store the information inside of a list. Trying to remove all of the values not equal to zero led me to list comprehension, but now, I'm stuck on how to write print code that allows the output to look like it should above. Any ideas?

Here is my code currently:

change = int(input())

dollars = change // 100
quarters = change % 100 // 25
dimes = change % 100 % 25 // 10
nickles = change % 100 % 25 % 10 // 5
pennies = change % 100 % 25 % 10 % 5 // 1

list = [dollars, quarters, dimes, nickles, pennies]

no_zero_in_list = [x for x in list if x != 0]
print(*no_zero_in_list)
Barmar
  • 741,623
  • 53
  • 500
  • 612
toinfinity
  • 21
  • 5
  • 1
    Don't use `list` or the names of other [built-ins](https://docs.python.org/3/library/functions.html) as variable names. It shadows the built-in and can lead to unexpected behavior down the road. – MattDMo May 18 '23 at 22:41

2 Answers2

1

Put the results in a dictionary. Then you can loop over the dictionary, skipping the values that are 0.

results = {
    "Dollars": dollars,
    "Quarters": quarters,
    "Dimes": dimes,
    "Nickels": nickels,
    "Pennies": pennies
}

for coin, amount in results.items():
    if amount != 0:
        print(f"{amount} {coin}")

If you want proper pluralization of the coin names, see Plural String Formatting

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You could work with dictionaries (don't!), or better use simpler structures and no lists. Something along the lines:

if pennies > 0:
    ...

This task doesn't require any lists or other magic. It does however require that you understand how indentation works.

Chr L
  • 89
  • 4