0
I’m analyzing an algorithm that returns the minimum number of coins to be used from a penny value.
def numero_moedas(centavos):
if centavos < 1:
return 0
moedas = [50, 25, 10, 5, 1]
n_moedas = 0
for moeda in moedas:
n_moedas += centavos // moeda
centavos = centavos % moeda
if centavos == 0:
break
return n_moedas
However, I need to display which coins were used among the minimum number of coins. For example:
In[1]: numero_moedas(31)
Out[1]: 3, [25, 5, 1]
What would be the logic needed to obtain this list of coins used?
The idea was to return a list with only the coins used, but I believe that with the dictionary became easier hehe
– Sidney Ramos
I edited the answer, maybe this other code better answer the question.
– Andre
Perfect!
moedas_utilizadas.extend([moeda] * n_moedas)
was the logic I wasn’t getting. Thank you!– Sidney Ramos
Why didn’t you start with the
n_moedas = 0
?– Sidney Ramos
@Sidney, I don’t understand. I used
n_moedas
only to count the number of coins being used within the loop, not the total. Even before you edited the code.– Andre
Before, the
n_moedas
returned only the min amount of coins needed. After its implementation, then_moedas
became 1. But soon I saw that you implemented the countern_moedas_total += n_moedas
– Sidney Ramos