文章详情

背景

在计算机专业的面试中,面试官往往会提出一些具有挑战性的旨在考察者的实际编程能力和解决能力。是一道常见的业务上BUG一条的面试题,我们将对其进行深入解析,并提供详细的答案。

陈述

假设你正在参与一个在线购物平台的后端开发工作。该平台有一个功能,用户可以添加商品到购物车中。系统设计如下:当用户点击添加商品到购物车按钮时,系统会检查购物车中是否已存在该商品,存在,则增加商品的数量;不存在,则将该商品添加到购物车中,并设置数量为1。是一个简化的代码片段,用于实现上述功能:

python

class ShoppingCart:

def __init__(self):

self.items = {}

def add_item(self, item_id, quantity=1):

if item_id in self.items:

self.items[item_id] += quantity

else:

self.items[item_id] = quantity

# 示例使用

cart = ShoppingCart()

cart.add_item("apple", 2)

cart.add_item("banana", 1)

print(cart.items) # 应输出:{'apple': 2, 'banana': 1}

上述代码中存在一个BUG,请该BUG,并给出修改后的代码。

BUG解析

在上述代码中,BUG出`add_item`方法中。当用户添加商品到购物车时,商品已存在,则直接将数量加上用户指定的数量。用户尝试添加的商品数量为负数,这个BUG会导致购物车中的商品数量出现错误。

用户尝试添加商品"apple"时指定数量为-2,根据原始代码,`self.items[item_id]`将会从2变为0,而不是保持为2。这显然不符合业务逻辑。

修改后的代码

为了修复这个BUG,我们需要在`add_item`方法中添加一个检查,确保添加的商品数量不能为负数。是修改后的代码:

python

class ShoppingCart:

def __init__(self):

self.items = {}

def add_item(self, item_id, quantity=1):

if item_id in self.items:

if quantity < 0:

raise ValueError("Cannot add negative quantity of items.")

self.items[item_id] += quantity

else:

if quantity <= 0:

raise ValueError("Cannot add zero or negative quantity of items.")

self.items[item_id] = quantity

# 示例使用

cart = ShoppingCart()

cart.add_item("apple", 2)

cart.add_item("banana", 1)

print(cart.items) # 应输出:{'apple': 2, 'banana': 1}

# 尝试添加负数数量

try:

cart.add_item("apple", -2)

except ValueError as e:

print(e) # 输出:Cannot add negative quantity of items.

# 尝试添加零数量

try:

cart.add_item("apple", 0)

except ValueError as e:

print(e) # 输出:Cannot add zero or negative quantity of items.

通过这种,我们确保了只有当用户尝试添加正数或零数量的商品时,购物车中的商品数量才会被正确更新。

在面试中遇到这类业务上BUG一条考察的是者对细节的关注程度和解决的能力。通过仔细分析代码,识别出潜在的错误,并提出有效的解决方案,是计算机专业面试中非常重要的技能。在上述中,我们通过添加简单的条件检查,成功地修复了BUG,并保证了程序的健壮性。

发表评论
暂无评论

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