What is the logic required to obtain the coins used in my algorithm?

Asked

Viewed 33 times

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?

1 answer

0


It depends on the way you want the output. If you intend to use a dictionary to associate the coins with the required number, simply replace the n_moedas, the logic is basically the same:

def numero_moedas(centavos):
    n_moedas_total = 0
    n_cada_moeda = {50: 0, 25: 0, 10: 0, 5: 0, 1: 0}

    if centavos < 1:
        return n_moedas_total, n_cada_moeda

    for moeda in n_cada_moeda:
        n_moedas = centavos // moeda
        centavos = centavos % moeda
        n_moedas_total += n_moedas
        n_cada_moeda[moeda] = n_moedas
        if centavos == 0:
            break

    return n_moedas_total, n_cada_moeda

Or for a result more like the question, create a list and add the currencies accounted for in your loop:

def numero_moedas(centavos):
    n_moedas_total = 0
    moedas_utilizadas = []

    if centavos < 1:
        return n_moedas_total, moedas_utilizadas

    moedas = [50, 25, 10, 5, 1]

    for moeda in moedas:
        n_moedas = centavos // moeda
        centavos = centavos % moeda
        n_moedas_total += n_moedas
        moedas_utilizadas.extend([moeda] * n_moedas)
        if centavos == 0:
            break

    return n_moedas_total, moedas_utilizadas
  • The idea was to return a list with only the coins used, but I believe that with the dictionary became easier hehe

  • I edited the answer, maybe this other code better answer the question.

  • Perfect! moedas_utilizadas.extend([moeda] * n_moedas) was the logic I wasn’t getting. Thank you!

  • Why didn’t you start with the n_moedas = 0?

  • @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.

  • Before, the n_moedas returned only the min amount of coins needed. After its implementation, the n_moedas became 1. But soon I saw that you implemented the counter n_moedas_total += n_moedas

Show 1 more comment

Browser other questions tagged

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