2014-11-23 139 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 2014-11-23 22:46:34

回答

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 。 – 2014-11-23 22:52:09

+0

都不愿我,但是这就是该方法在原来的问题描述说。如果有人进入了-1项目的价格 – DanielGibbs 2014-11-23 22:54:00

+1

要有趣... :)(但是,是的 - 这是什么OP曾表示:P) – 2014-11-23 22:54:47

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

使用minoperator.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'))