Python 3.x 在实例变量中查找最低值
我试图返回购物车中最便宜的商品,但是,我无法以任何方式访问价目表 使用和Python 3.x 在实例变量中查找最低值,python-3.x,Python 3.x,我试图返回购物车中最便宜的商品,但是,我无法以任何方式访问价目表 使用和 class Item: """ An instance of an item """ def __init__(self, price): """ (Item, float) Initialize an Item """ self.price = price 请发布两个类的完整代码。我不会在这里返回-1。。如果购物车中没有任何物品,最便宜的
class Item:
""" An instance of an item """
def __init__(self, price):
""" (Item, float)
Initialize an Item
"""
self.price = price
请发布两个类的完整代码。我不会在这里返回-1。。如果购物车中没有任何物品,最便宜的物品是0。我也不会,但这是原始问题中方法的描述所说的。如果有人输入物品价格为-1,那会很有趣…:但是是的-这是OP所说的:p
class Item:
""" An instance of an item """
def __init__(self, price):
""" (Item, float)
Initialize an Item
"""
self.price = price
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
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)
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'))