user2368334
user2368334

Reputation: 73

In Python, what is the easiest way to find the smallest value in a list which contains both strings and floats?

My code asks for a list of products or loads them from a file. Then, I need to find which of the values is the smallest, and if there are equally small elements, choose a random one. However, I still need to link the value to its relevant string. So far I have:

def checkPrices(products):

    for x in range(len(products)):
        if (x)%3 == 0:
            name = str(products[x])
            print(name)
        elif (x+1)%3 == 0:
            quantity = int(products[x])
            print(quantity)
            pricePerUnit = str(format(price/quantity, '.2f'))
            print(name + " is $" + pricePerUnit + " per unit")

        elif (x)%1 == 0:
                price = float(products[x])
                print(price)

How can I extend this so that I can find the smallest price per unit and then print something like:

I would recommend product1

Upvotes: 1

Views: 138

Answers (2)

Jon Clements
Jon Clements

Reputation: 142206

Group your products into three to unflatten it:

grouped = zip (*[iter(products)] * 3)

Then take the min...

recommended = min(grouped, key=lambda (name, qty, price): float(price) / int (qty))[0] 

Upvotes: 1

Amber
Amber

Reputation: 527073

I would recommend that instead of storing all 3 values for everything in a flat list, like you seem to be...

["product1", "3", "0.15", "product2", "4", "0.40"]

...that you instead store them as a list of tuples:

[("product1", 3, 0.15), ("product2", 4, 0.40)]

This keeps the logical grouping per-item, and lets you do things like...

product_info = [("product1", 3, 0.15), ("product2", 4, 0.40)]
cheapest_product = min(product_info, key=lambda product: product[2] / product[1])

product_name, quantity, total_price = cheapest_product
print "I would recommend %s" % product_name

Note: If all you have is that flat list and you want to convert it to a tuple list...

products = ["product1", "3", "0.15", "product2", "4", "0.40"]
products_iter = iter(products)
product_tuples = zip(products_iter, products_iter, products_iter)
product_info = [(i[0], int(i[1]), float(i[2]) for i in product_tuples]

and product_info will now be the list of tuples I described above.

Upvotes: 3

Related Questions