文章详情

在一家电商公司担任开发工程师的你,负责开发了一款订单管理系统。用户反馈在提交订单时,系统出现了无确计算总价的情况。具体来说,当用户在购物车中添加了不同类型的商品,系统在计算总价时,将某些商品的价格重复计算了两次。是一个简化的代码片段,用于处理订单中的商品总价计算:

python

class ShoppingCart:

def __init__(self):

self.items = []

def add_item(self, item):

self.items.append(item)

def calculate_total(self):

total = 0

for item in self.items:

total += item.price

return total

class Item:

def __init__(self, name, price):

self.name = name

self.price = price

# 示例使用

cart = ShoppingCart()

cart.add_item(Item("Laptop", 1000))

cart.add_item(Item("Mouse", 50))

cart.add_item(Item("Keyboard", 80))

cart.add_item(Item("Laptop", 1000)) # 重复添加一个Laptop

print(cart.calculate_total()) # 预期输出:2100,但实际输出为:2200

请分析上述代码,找出导致的原因,并提出相应的解决方案。

分析

在上述代码中,`ShoppingCart` 类负责管理购物车中的商品,并通过 `calculate_total` 方法计算总价。`Item` 类代表一个商品,包含名称和价格。出 `ShoppingCart` 类的 `calculate_total` 方法中。

当 `ShoppingCart` 的 `items` 列表中包含重复的商品时,在示例中重复添加了一个 "Laptop" 商品,`calculate_total` 方将该商品的价格重复计算两次,导致总价计算错误。

原因分析

在 `calculate_total` 方法中,代码使用了逻辑来计算总价:

python

total = 0

for item in self.items:

total += item.price

这段代码会遍历 `ShoppingCart` 的 `items` 列表,并对每个 `Item` 对象的 `price` 属性进行累加。由于列表 `items` 可能包含重复的商品,同一商品的价格会被重复添加到 `total` 中。

解决方案

为了解决这个我们可以采用几种方法之一:

1. 使用集合(Set)来存储商品,确保每个商品只计算一次价格。

2. 在添加商品到购物车时,检查商品是否已存在,存在则不再添加。

3. 使用字典(Dictionary)来存储商品和其对应的价格,确保每个商品只计算一次价格。

是使用集合来解决这个的代码示例:

python

class ShoppingCart:

def __init__(self):

self.items = set()

def add_item(self, item):

if item not in self.items:

self.items.add(item)

def calculate_total(self):

total = 0

for item in self.items:

total += item.price

return total

# 示例使用

cart = ShoppingCart()

cart.add_item(Item("Laptop", 1000))

cart.add_item(Item("Mouse", 50))

cart.add_item(Item("Keyboard", 80))

cart.add_item(Item("Laptop", 1000)) # 重复添加一个Laptop

print(cart.calculate_total()) # 输出:2100,正确计算总价

在这个解决方案中,我们使用了一个集合 `self.items` 来存储购物车中的商品。在添加商品时,我们检查该商品是否已经存在于集合中,不存在,则将其添加到集合中。这样,即使用户重复添加同一个商品,集合中也只会存储一个实例,从而确保了价格的正确计算。

发表评论
暂无评论

还没有评论呢,快来抢沙发~