【发布时间】:2019-03-19 05:34:33
【问题描述】:
我正在做一个课程'discrete optimization course 其中,在课程中使用了一个名为 Minizinc 的工具来解决这些问题。
我想将类示例翻译成python,从这个开始:
v = {'hammer':6, 'wrench':10, 'screwdriver':8, 'towel':40}
w = {'hammer':13, 'wrench':21, 'screwdriver':17, 'towel':100}
q = {'hammer':1000, 'wrench':400, 'screwdriver':500, 'towel':150}
limit = 1000
items = list(sorted(v.keys()))
# Create model
m = LpProblem("Knapsack", LpMaximize)
# Variables
x = LpVariable.dicts('x', items, lowBound=0, upBound=1, cat=LpInteger)
# Objective
m += sum(v[i]*x[i] for i in items)
# Constraint
m += sum(w[i]*x[i] for i in items) <= limit
# Optimize
m.solve()
# Print the status of the solved LP
print("Status = %s" % LpStatus[m.status])
# Print the value of the variables at the optimum
for i in items:
print("%s = %f" % (x[i].name, x[i].varValue))
# Print the value of the objective
print("Objective = %f" % value(m.objective))
但这是一个错误的答案,因为它只采用了一种。 如何将每个项目 (dict q) 的可用数量添加到约束中?
【问题讨论】:
标签: python optimization linear-programming pulp