Python Forum
Factoring input into listed frequencies
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Factoring input into listed frequencies
#5
In line number 6 you've an error:
num = (int)(amount / each_coin)
this should be num = int(amount / each_coin)).

First I did not understand why it did not thrown an error. But the explanation is very easy.
(int) returns the built-in function int. The parenthesis after int, are calling the returned int function.
If you have written (int,), it makes a tuple with the int function as a single element.

In line 7 you append num to change, but outside of the loop. You get only the last value.
In line 8 you set amount to the new amount. But this is also outside of the loop. So, only the last value will be evaluated, but it's not used inside the loop. Line 7 and 8 have to be indented.

A corrected version:
def pay_with_coins( amount ):
    all_coins = [2.00, 1.00, 0.50, 0.20, 0.10, 0.05, 0.02, 0.01]
    change = []
    for each_coin in all_coins:
        num = (int(amount / each_coin))
        change.append(num)
        amount = round(amount - (num * each_coin), 2)
    return change
I made a little different implementation.
Instead of using float, I use int for the smallest currency unit. The cause: 0.1 + 0.2 == 0.30000000000000004.
The function divmod does what you want to have. The function divmod returns the result and the rest.
If you still want to work with floats, you should look into the module decimal.

print(divmod(10, 3))
Output:
(3,1)
10 divided by 3 == 3 + rest 1

def pay_with_coins(amount):
    amount = int(amount * 100)
    # convert amount into the smallest currency unit (cent)
    all_coins_cent = [200, 100, 50, 20, 10, 5, 2, 1]
    # values as integers in the smallest currency unit
    change = []
    for each_coin in all_coins_cent:
        factor, rest = divmod(amount, each_coin)
        change.append(factor)
        amount = rest
        # print(rest)
    return  {'change': change, 'rest': rest}

print(pay_with_coins(5.18))
Additionally I return a dict, just to see if there is any rest left.
This should not happen, because we have also 1 cent. If you remove this coin,
the rest will be one cent.
If you remove this coin,
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: Factoring input into listed frequencies - by DeaD_EyE - Nov-14-2018, 09:55 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020