MST

星途 面试题库

面试题:Python Web开发中复杂条件下if语句的优化

假设在一个电商Web应用中,根据用户的会员等级、购买金额、商品类别等多个条件来决定是否给予折扣。请使用Python在Django框架下,编写代码实现该逻辑,并说明如何优化多个if条件判断,以提高代码执行效率和可读性。
11.7万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

1. 在Django框架下实现折扣逻辑代码

首先,假设我们有一个models.py文件定义了相关模型,例如:

from django.db import models


class User(models.Model):
    MEMBERSHIP_LEVEL_CHOICES = (
        ('bronze', 'Bronze'),
        ('silver', 'Silver'),
        ('gold', 'Gold'),
    )
    membership_level = models.CharField(max_length=10, choices=MEMBERSHIP_LEVEL_CHOICES)


class Order(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    purchase_amount = models.DecimalField(max_digits=10, decimal_places=2)
    product_category = models.CharField(max_length=50)

然后在视图函数(假设在views.py)中实现折扣逻辑:

def calculate_discount(order):
    discount = 0
    if order.user.membership_level == 'gold':
        discount += 0.1
    elif order.user.membership_level =='silver':
        discount += 0.05
    if order.purchase_amount >= 100:
        discount += 0.03
    if order.product_category == 'electronics':
        discount += 0.02
    return discount

2. 优化多个if条件判断的方法

2.1 使用字典映射

将判断条件和对应的折扣值通过字典映射起来,这样可以减少冗长的if - elif链。例如:

membership_discounts = {
    'gold': 0.1,
  'silver': 0.05
}
category_discounts = {
    'electronics': 0.02
}


def calculate_discount_optimized(order):
    discount = 0
    discount += membership_discounts.get(order.user.membership_level, 0)
    if order.purchase_amount >= 100:
        discount += 0.03
    discount += category_discounts.get(order.product_category, 0)
    return discount

2.2 策略模式

将每个判断条件封装成一个单独的策略函数,然后通过一个列表或字典来管理这些策略。

def membership_discount(order):
    membership_discounts = {
        'gold': 0.1,
      'silver': 0.05
    }
    return membership_discounts.get(order.user.membership_level, 0)


def amount_discount(order):
    return 0.03 if order.purchase_amount >= 100 else 0


def category_discount(order):
    category_discounts = {
        'electronics': 0.02
    }
    return category_discounts.get(order.product_category, 0)


def calculate_discount_strategy(order):
    strategies = [membership_discount, amount_discount, category_discount]
    discount = 0
    for strategy in strategies:
        discount += strategy(order)
    return discount

通过以上方式,代码的执行效率和可读性都能得到提升。使用字典映射减少了if - elif的嵌套,而策略模式将复杂逻辑进行了模块化,更易于维护和扩展。