邏輯限制條件練習
你的客戶在接下來一個月內訂購了 6 項產品需要出貨。你需要安排多趟卡車運送,才能把所有產品送達。每輛卡車的重量上限為 25,000 磅。基於現金流考量,你希望裝載在卡車上的產品組合要在可裝下的前提下,達到最高獲利。
| Product | Weight (lbs) | Profitability ($US) |
|---|---|---|
| A | 12,583 | 102,564 |
| B | 9,204 | 130,043 |
| C | 12,611 | 127,648 |
| D | 12,131 | 155,058 |
| E | 12,889 | 238,846 |
| F | 11,529 | 197,030 |
已為你建立了兩個 Python 字典 weight 和 prof,以及一個清單 prod,分別包含每個產品的重量、獲利與名稱。你可以在主控台中查看。
本練習屬於課程
Python 的供應鏈分析
練習說明
- 加入一個限制條件,確保卡車總重量小於或等於 25,000 磅。
- 再加入一個限制條件,讓模型在 D、E、F 三個產品之間「最多只會」選擇一個。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Initialized model, defined decision variables and objective
model = LpProblem("Loading Truck Problem", LpMaximize)
x = LpVariable.dicts('ship_', prod, cat='Binary')
model += lpSum([prof[i] * x[i] for i in prod])
# Define Constraint
model += lpSum([weight[i] * x[i] for i in prod]) ____ ____
model += ____
model.solve()
for i in prod:
print("{} status {}".format(i, x[i].varValue))