Home > Software engineering >  search for the lowest priced item function
search for the lowest priced item function

Time:06-07

I'm adding a function to a class to output the item with the lowest price but what I'm getting are all the prices. See photo and code. What am I missing on the code?

def get_low_price(self):
        self.get_total_toys()
        #To check if toybox is empty or not        
        if self.total > 0:                    
            
            msg = f'The toy box contains {self.total} toys\n'
            for a_toy in self.all_toys:            
                
                self.get_total_cost()
                msg  = f'A {(a_toy.colour).lower()} {a_toy.name} which cost ${a_toy.price:.2f}\n'               

                for i in [a_toy.price]:
                    i = ([i])
                print(min(i))

                
            return f'{msg}Total cost: ${self.cost_total:.2f}'


CodePudding user response:

This inner loop isn't doing anything useful:

            for i in [a_toy.price]:
                i = ([i])
            print(min(i))

Here a_toy is already just a single toy. Looping over a new list containing only its price doesn't accomplish anything you could get just by accessing a_toy.price directly, and rebinding the loop variable i to another new list (in extraneous parentheses) doesn't add anything.

I think you want to move all of the min-finding logic outside of the earlier loop, unless you want to compare prices yourself. Instead, you can use just one min call, outside of the loop:

       for a_toy in self.all_toys:    # don't include the stuff below in this loop
            ...                   

       cheapest = min(self.all_toys, key=lambda t: t.price)        # find cheapest

       # do something down here with cheapest, or cheapest.name, maybe

CodePudding user response:

I didn't understand what exactly you are trying to do using the for loop in that method. If you are thinking that i = ([i]) is going to append price to a list then it's wrong. Use the below logic and rewrite your method. It will work.

toys = {"doll": 5, "hulk": 10, "teddy": 15}

cheapest_toy_name = ""
cheapest_toy_price = float("inf")
for k, v in toys.items():
    if cheapest_toy_price > v:
        cheapest_toy_price = v
        cheapest_toy_name = k
print(cheapest_toy_name)
  • Related