Divide a number into smaller specific numbers

Viewed 121

I want to create a program that takes in an input from a user and returns the value in bills

i.e. if the input is 110, I would want to program to output:

1 x 100
1 x 10

and if the input is 87 I want to program to output

4 x 20
1 x 5
2 x 1

etc. Anyone know how to do this?

2 Answers

You can use integer division to get the how often each bill fits.

bills = [20, 5, 1]

input = 87

for bill in bills:
    integer_div = input // bill
    if integer_div > 0:
        print(f'{integer_div} x {bill}')
        input -= integer_div * bill

Result

4 x 20
1 x 5
2 x 1
def change(amount, bills):
    money = {}
    for bill in bills:
        bill_count = amount/bill
        money[bill] = bill_count
        amount -= bill * bill_count
    return money

result = change(87, [20, 5, 1])
for coin, amount in result.items():
    if amount != 0:
        print("%d X %d" % (amount, coin))

will make the required result.

Related