Euro banknote sorting program? Python

Asked

Viewed 263 times

2

def Dinheiro_vivo(x):

while x > 0.00:
    if x>=50.0:
        print( x//50,('notas de 50 euros'))
        n = x % 50
    elif x<50 and x >=20:
        print (y//20,('notas de 20 euros'))
        x= x %20
    elif  x<20 and x >=10:
        print (x//10,('notas de 10 euros'))
        x = x % 10
    elif  x<10 and x >=5:
        print( x//5, ('notas de 5 euros'))
        x = x% 5
    elif x<5 and x>=2:
        print( x//2, ('moedas de 2 euros'))
        x = x % 2
    elif  x<2.0 and x>=1.0:
        print( x//1,('moedas de um euro'))
        x= x%1
    elif x<1.0 and x >=0.50:
        print( x//0.50,('moedas de 50 centimos'))
        x = x %0.50
    elif x<0.50 and x>=0.20:
        print( x//0.20,('moedas de 20 centimos'))
        x = x%0.20
    elif x<0.20 and x>= 0.10:
        print( x//0.10,('moedas de 10 centimos'))
        x = x%0.10
    elif  x<0.10 and x>=0.05:
        print(x//0.05,('moedas de 5 centimos'))
        x= x % 0.05
    elif x<0.05 and x>=0.02:
        print( x//0.02,('moedas de 2 centimos'))
        x = x %0.02
    else:
        print ( x ,('moedas de 1centimos'))

my exercise is to program a function in Python to sort the number of banknotes and coins to which my number (x) corresponds but give me an infinite loop, I need help.

  • The program displays the amount of banknotes and coins corresponding to an amount of X Euros as efficiently as possible, that would be ?

1 answer

2

Comparisons between type values float are hell! Avoid them!

Isolating your infinite loop:

x = 10.5;
while x > 0.0:
    x = x % 3 

Instead of working with Euros, try working with Centimos by multiplying the value in Euros by 100:

cents = int( eur * 100 )

Working with values in Centimos dispenses comparisons between values float in its implementation.

In Python things can be very elegant:

def exibirDinheiroVivo( lst ):
    for i in lst:
        if i[0] > 50 : tp, un, vl = "Nota", "Euro", i[0] / 100
        if i[0] <= 50 : tp, un, vl = "Moeda", "Centimo", i[0]
        if vl > 1 : un += "s"
        if i[1] > 1 : tp += "s"
        print( "%d %s de %d %s" % ( i[1], tp, vl, un ) )

def calcularDinheiroVivo( eur ):
    vals = [ 5000, 2000, 1000, 500, 100, 50, 20, 10, 5, 2, 1 ]
    c = int(eur * 100)
    res = []
    while c > 0:
        for v in vals :
            if c >= v :
                res.append([ v, c // v ]);
                c = c % v
                break
    return res


c = calcularDinheiroVivo(123.43);
exibirDinheiroVivo(c);

Exit:

2 Notas de 50 Euros
1 Nota de 20 Euros
3 Notas de 1 Euro
2 Moedas de 20 Centimos
1 Moeda de 2 Centimos
1 Moeda de 1 Centimo
  • 2

    Just and necessary emphasis on this: Comparisons between float values are hell! Avoid them!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.