Search code examples
pythonpython-3.xmodulusgreatest-common-divisorfloor-division

Using % and // to find divisors


I'm working on a small assignment. The task is to program a money dispenser calculator. A basic version might produce the following output:

Initial amount ($): 348
$100
$100
$100
$20
$20
$5
$2
$1

Here's my attempt:

#Pseudocode:
"""
Ask user for amount
For each demonination in [100, 50, 20, 10, 5, 2, 1]:
    Integer-divide amount by demonination
    Subtract demonination from amount to leave residual
    If residual // demonination > 1, add 1 to the count of this note, and repeat
    Otherwise go to the next denomination
"""


def find_denom(amount):
    number_of_notes = 0
    banknotes = [100, 50, 20, 10, 5, 2]
    for note in banknotes:
        residual = (amount // note)
        if residual // note > 1:
            number_of_notes += 1
    return residual, number_of_notes

amount = int(input("Enter initial amount ($): "))
residual, number_of_notes = find_denom(amount)

If I enter 348 as the initial amount, I get the following variable values: amount=348, number_of_notes=3, which is correct for the number of $100 notes in amount, and residual=174.

I'm just trying to get my find_denom function working first, but I'm not sure where to go from here.


Solution

  • In other to achieve what you want, use can use this function

    def find_denom(amount):
        banknotes = [100, 50, 20, 10, 5, 2, 1]
        for note in banknotes:
            counter = 0 # reassign zero to counter for every loop
            if note <= amount:
                number_of_notes = amount // note  # get the number of each note in amount
                amount = amount % note  # assign the remaining amount to amount
                while counter < number_of_notes: # check it the number of counter has exceeded the number of notes 
                    print('$'+str(note)) #convert note to str and concatenate $ with it and display the note
                    counter += 1
    
    amount = int(input("Enter initial amount ($): "))
    find_denom(amount)