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

PuLP优化中遍历多字典替换硬编码方案的实现方法咨询

PuLP优化硬编码方案的灵活改造实现

前置修正提示

你原有代码中使用集合{}存储part_numbers、employees等需要按索引访问的序列,集合本身是无序且不支持下标索引的,首先需要将这类结构改为列表[]保证取值顺序符合预期。另外你给出的效率列表第一个值为85,判定为笔误,后续代码中统一修正为0.85,可按需调整。

改造后完整可运行代码

import pulp

# 基础配置数据,后续新增/删除条目只需修改这部分即可
part_numbers = ["Part A", "Part B"]
employees = ["Employee A", "Employee B", "Employee C", "Employee D", 
             "Employee E", "Employee F", "Employee G", "Employee H"]
# 零件对应加工耗时,顺序和part_numbers一一对应
exptime = [20, 10]
# 原始效率列表,前8个为Part A对8名员工的效率,后8个为Part B对8名员工的效率
raw_eff = [0.85, .75, .5, .75, .59, .40, .87, .37, 
           .65, .85, .85, .5, .4, .8, .3, .92]
# 加工效率双层字典,直接用(零件, 员工)作为键取值,避免索引计算错误
efficiency = {}
for p_idx, part in enumerate(part_numbers):
    for e_idx, emp in enumerate(employees):
        efficiency[(part, emp)] = raw_eff[p_idx * len(employees) + e_idx]

# 初始化优化模型
model = pulp.LpProblem("Production_Optimization", pulp.LpMinimize)
# 定义决策变量:每个员工生产每种零件的数量
qty_produced = pulp.LpVariable.dicts(
    "produce_qty",
    [(part, emp) for part in part_numbers for emp in employees],
    lowBound=0,
    cat="Integer" # 如果允许非整数产量可改为Continuous
)

# 目标函数:所有零件-员工组合的平均生产耗时最小
model += pulp.lpSum([
    exptime[p_idx] * qty_produced[(part, emp)] / efficiency[(part, emp)]
    for p_idx, part in enumerate(part_numbers)
    for emp in employees
]) / (len(part_numbers) * len(employees))

# 约束:每个员工总生产耗时不超过530
for emp in employees:
    model += pulp.lpSum([
        exptime[p_idx] * qty_produced[(part, emp)] / efficiency[(part, emp)]
        for p_idx, part in enumerate(part_numbers)
    ]) <= 530

# 求解模型
model.solve()
print("求解状态:", pulp.LpStatus[model.status])

核心改造逻辑

  • 数据结构优化:将原本分散的效率值转换为以(零件编号, 员工)为键的字典,无需手动计算索引位置,彻底避免索引错位导致的计算错误
  • 目标函数通用化:通过双层循环遍历所有零件和员工的组合自动累加计算,新增/删除零件或员工时不需要修改目标函数代码
  • 约束自动生成:遍历所有员工自动生成单人工时上限约束,员工数量变更时无需手动增减约束条目

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 13:45:10