Find largest element index in the list

Asked

Viewed 84 times

1

I am putting together a code that creates a list with 3 items of purchase, and within this list some tuples with the names of the products and the respective prices. I want to find the lowest price and display, along with the product name. It must be some silly adjustment, but I could not identify how I can link the lowest price to the corresponding product name. Can help?

    lista_de_compras = [
    (('Batata'), (float(input('Qual o preço da batata? R$ ')))),
    (('Cenoura'), (float(input('Qual o preço da cenoura? R$ ')))),
    (('Vagem'), (float(input('Qual o preço da vagem? R$ '))))
]

menor_valor_da_lista = min(lista_de_compras[0][1], lista_de_compras[1][1], lista_de_compras[2][1])

print(f'Você deve levar a **___** que custa R${menor_valor_da_lista}')

3 answers

2


Choose the appropriate data structure

You created a list of tuples, but if the idea is to map each product with its respective price, a dictionary seems more appropriate.

Not only does it make more sense for this case, it will also make the solution much easier. It would look like this:

lista_de_compras = {}
for produto in ['batata', 'cenoura', 'vagem']:
    lista_de_compras[produto] = float(input(f'preço de {produto}, R$ '))

mais_barato = min(lista_de_compras, key=lista_de_compras.get)

print(f'Você deve levar {mais_barato} que custa R${lista_de_compras[mais_barato]:.2f}')

To print the price, I used the formatting options, to print always to two decimal places.

When using min, i state that I want to use lista_de_compras.get, what makes the prices are compared instead of the names. The result is the product that has the lowest price, and then just print it.

It just doesn’t solve tie cases, when more than one product is cheaper. In that case, just go through the dictionary and print everyone that has the same price:

mais_barato = min(lista_de_compras, key=lista_de_compras.get)

menor_preco = lista_de_compras[mais_barato]

print(f'produtos mais baratos, custam R${menor_preco:.2f}')
for produto, preco in lista_de_compras.items():
    if preco == menor_preco:
        print(produto)

Unless you already receive the list of tuples that way, there is no reason to use it, as a dictionary makes much more sense for this case. A another answer even shows that it can be solved with the list, but it becomes unnecessarily more complicated, and all because it is not the most appropriate data structure to solve the problem.

Choose the appropriate data structure is halfway towards a better code.

0

You can use the function map obtain a new list containing the prices of each product. Just pass in the first parameter a function receive an item (tuple) and return the second element of this item (price). See the code below:

valores = list(map(lambda item: item[1], lista_de_compras))

Since you’re a beginner and maybe the above code is still a little bit advanced for you, here’s another code that’s equivalent, but a little bit bigger.

def obter_valores(lista):
    valores = []

    for item in lista:
        valores.append(item[1])
        
    return valores

Once you have obtained all the values we need to know the lowest value of the right list? For this, we can use the function min that returns the smallest value of an eternal.

min([5, 7, 8, 2, 9, 3, 4])  # Retorna o valor 2

As the goal is to get the item completely (tuple), we can use the method index from the list of values to obtain the index of the value, which will be the same as the item in the shopping list.

indice_do_menor_valor = valores.index(min(valores))

Now just get the item through that index and ready. Below is the full code:

valores = list(map(lambda item: item[1], lista_de_compras))
indice_do_menor_valor = valores.index(min(valores))

nome, valor = lista_de_compras[indice_do_menor_valor]
print(f'Você deve levar a {nome} que custa R${valor}')

0

I would use a dictionary instead of a tuple and leave the code like this:

lista_de_compras = {
    ('Batata'): (float(input('Qual o preço da batata? R$ '))),
    ('Cenoura'): (float(input('Qual o preço da cenoura? R$ '))),
    ('Vagem'): (float(input('Qual o preço da vagem? R$ ')))
}

menor_valor_da_lista = min(lista_de_compras, key=lista_de_compras.get)

print(f'Você deve levar a {menor_valor_da_lista} que custa R${lista_de_compras[menor_valor_da_lista]}')

Browser other questions tagged

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