2014-11-23 3 views
0
class ShoppingCart: 

    def __init__(self): 
     self.cart = [] 

    def add_item(self, item): 
     """ (ShoppingCart, Item) -> NoneType 
     Adds an item to the cart. 
     """ 
     self.cart.append(item) 

    def show_cheapest_item(self): 
     """ (ShoppingCart) -> int 
     Return the cheapest item in the cart, or -1 if no items are in the cart 
     """ 
     # my point of confusion 

class Item: 

    """ An instance of an item """ 
    def __init__(self, price): 
     """ (Item, float) 
     Initialize an Item 
     """ 
     self.price = price 

Я пытаюсь вернуть дешевый товар в корзину, однако, я не могу получить доступ к прайс-лист в любом случае.найти наименьшее значение внутри экземпляра переменной

+0

Пожалуйста, пост полный код обоих классов – alfasin

ответ

0
def show_cheapest_item(self): 
    """ (ShoppingCart) -> int 
    Return the cheapest item in the cart, or -1 if no items are in the cart 
    """ 
    if len(self.cart) == 0: 
     return -1 
    cheapest_item = self.cart[0] 
    for item in self.cart[1:]: 
     if item.price < cheapest_item.price: 
      cheapest_item = item 
    return cheapest_item 
+0

я бы не вернуться -1 здесь .. если нет ничего в корзине самый дешевый элемент 0 –

+0

И я тоже, но это то, что сказано в описании метода в исходном вопросе. – DanielGibbs

+1

Будьте интересны, если кто-то вошел в цену товара -1 ... :) (но да - это то, что ОП заявила: p) –

0
class ShoppingCart: 

    def __init__(self): 
     self.cart = [] 

    def add_item(self, item): 
     """ (ShoppingCart, Item) -> NoneType 
     Adds an item to the cart. 
     """ 
     self.cart.append(item) 

    def show_cheapest_item(self): 
     """ (ShoppingCart) -> int 
     Return the cheapest item in the cart, or -1 if no items are in the cart 
     """ 
     return -1 if len(self.cart) == 0 else min(self.cart) 
0

Использование min и operator.attrgetter

import operator 

def show_cheapest_item(self): 
    """ (ShoppingCart) -> int 
    Return the cheapest item in the cart, or -1 if no items are in the cart 
    """ 
    return -1 if not self.cart else min(self.cart, key=operator.attrgetter('price')) 
Смежные вопросы