You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现按重量分段计费的运费计算器功能咨询

运费计算器实现方案

完整实现代码

from decimal import Decimal

prices = {
    "2": [Decimal(2), Decimal(37.00)],
    "5": [Decimal(5), Decimal(42.00)],
    "10": [Decimal(10), Decimal(53.00)],
    "15": [Decimal(15), Decimal(64.00)],
    "20": [Decimal(20), Decimal(74.00)],
    "25": [Decimal(25), Decimal(90.00)],
    "31.5": [Decimal(31.5), Decimal(101.00)]
}

# 预先将价格规则按重量升序排序,避免硬编码多段判断
sorted_price_rules = sorted(prices.values(), key=lambda x: x[0])
max_single_weight = sorted_price_rules[-1][0]
max_single_fee = sorted_price_rules[-1][1]

def calculate_single_package(mass):
    """计算单个不超过31.5kg包裹的对应运费"""
    for weight_limit, fee in sorted_price_rules:
        if mass <= weight_limit:
            return fee
    return max_single_fee

def calculate(mass):
    mass = Decimal(mass)
    total_fee = Decimal(0)
    # 超重拆包逻辑
    if mass > max_single_weight:
        # 计算满重包裹数量
        full_packages = int(mass // max_single_weight)
        total_fee += full_packages * max_single_fee
        # 计算剩余重量
        remainder = mass % max_single_weight
        if remainder == 0:
            return total_fee
        # 剩余重量单独计算一个包裹的运费
        total_fee += calculate_single_package(remainder)
        return total_fee
    # 未超重直接计算单个包裹运费
    return calculate_single_package(mass)

测试示例

print(calculate(0.5))  # 输出 37
print(calculate(31.5)) # 输出 101
print(calculate(32))   # 输出 138,符合题目示例要求
print(calculate(63))   # 输出 202,两个满重包裹
print(calculate(36))   # 输出 143,1个满重包裹+4.5kg(对应5kg档位)

逻辑说明

  • 无需硬编码多段if-elif判断,后续调整重量区间、运费价格仅需修改prices字典即可,代码逻辑自动适配
  • 全程使用Decimal类型计算,避免浮点精度误差导致的运费计算错误
  • 拆包逻辑符合要求:超重部分优先按最大限重包裹计算,剩余不足最大限重的部分按实际重量匹配对应档位运费

内容的提问来源于stack exchange,提问作者PersonPr7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 23:15:03