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

如何在Pulp BinPacking中添加约束,确保物品a与b不分配至同一箱子

How to Add "No Same Bin" Constraint for Items a and b in Pulp Bin Packing

Got it, let's break this down clearly—this is a common constraint to add in bin packing problems, and it's straightforward once you map it to your Pulp variable setup.

First, let's align on the typical variable structure most people use for bin packing in Pulp (if your existing code uses something similar, this will plug right in):

  • x[i][j]: Binary variable where x[i][j] = 1 means item i is placed in bin j, and 0 otherwise.
  • y[j]: Binary variable where y[j] = 1 means bin j is being used, 0 otherwise.

The Core Constraint Logic

To make sure items a and b never share a bin, we just need to enforce that for every single bin j, at most one of a or b can be assigned to it. Translating that into a linear constraint Pulp understands:
x[a][j] + x[b][j] ≤ 1 for all bins j.

Implementing This in Your Code

Let's say you already have:

  • A list of items (e.g., items = [a, b, c, d, ...] where a and b are your target items)
  • A list of bins (e.g., bins = list(range(total_bins)))
  • Your Pulp LpProblem instance named prob

Add this loop to your constraint-defining section:

# Replace a and b with the actual identifiers (indices or IDs) from your code
for j in bins:
    prob += pulp.LpConstraint(
        x[a][j] + x[b][j],
        pulp.LpConstraintLE,
        1,
        name=f"no_co_bin_{a}_{b}_bin_{j}"
    )

Quick Breakdown

  • For every bin j, we cap the sum of x[a][j] and x[b][j] at 1. Since both are binary (0 or 1), this means they can't both be 1 in the same bin—exactly what you need.
  • The name parameter is optional but super helpful for debugging if you ever need to inspect or tweak constraints later.

If Your Variable Setup Is Different

If you're using an integer variable for bin assignment (e.g., bin_assignment[i] which stores the bin number for item i), you can't use a direct != in Pulp. Instead, use this alternative approach:

for j in bins:
    # Ensure a and b aren't both assigned to bin j
    prob += pulp.LpConstraint(
        (bin_assignment[a] == j) + (bin_assignment[b] == j) ≤ 1,
        name=f"no_same_bin_{j}"
    )

Just drop this constraint block into your code after defining your variables and before calling prob.solve(), and it'll enforce that items a and b stay in separate bins.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:49:12