我正在尝试打印变量的值,定义为LpVariable(PuLP 1.6.1,Python 3.5)。 LpVariable可以选择将参数的类别设置为“整数”。但是,当我要求打印变量时,这不会产生值。 因此,我想解决一个问题:
from pulp import *
prob = LpProblem("Gadget Production", LpMinimize)
# Demand scheme x (Laptops), y (Phones), and z (Tablets)
x = [75, 125, 1000, 1500]
y = [120, 2000, 2000, 2000]
z = [50, 2000, 3000, 2000]
PL1 = LpVariable('Prod Laptop January', cat=int)
PL2 = LpVariable('Prod Laptop February', cat=int)
PL3 = LpVariable('Prod Laptop March', cat=int)
PP1 = LpVariable('Prod Phone January', cat=int)
PP2 = LpVariable('Prod Phone February', cat=int)
PP3 = LpVariable('Prod Phone March', cat=int)
PT1 = LpVariable('Prod Tablet January', cat=int)
PT2 = LpVariable('Prod Tablet February', cat=int)
PT3 = LpVariable('Prod Tablet March', cat=int)
# Inventory (I) of gadget (L, P, T), in month [i]:
IL1 = x[0] + PL1 - x[1]
IL2 = IL1 + PL2 - x[2]
IL3 = IL2 + PL3 - x[3]
IP1 = y[0] + PP1 - y[1]
IP2 = IP1 + PP2 - y[2]
IP3 = IP2 + PP3 - y[3]
IT1 = z[0] + PT1 - z[1]
IT2 = IT1 + PT2 - z[2]
IT3 = IT2 + PT3 - z[3]
# Constraints to meet demand scheme
prob += x[0] + PL1 >= x[1]
prob += IL1 + PL2 >= x[2]
prob += IL2 + PL3 >= x[3]
prob += y[0] + PP1 >= y[1]
prob += IP1 + PP2 >= y[2]
prob += IP2 + PP3 >= y[3]
prob += z[0] + PT1 >= z[1]
prob += IT1 + PT2 >= z[2]
prob += IT2 + PT3 >= z[3]
# Constraints to meet maximal production hours
prob += 5*PL1 + 2*PP1 + 4*PT1 <= 23000
prob += 5*PL2 + 2*PP2 + 4*PT2 <= 23000
prob += 5*PL3 + 2*PP3 + 4*PT3 <= 23000
# Overtime costs, function to be minimized
OT1 = (5*PL1 + 2*PP1 + 4*PT1) - 20000
OT2 = (5*PL2 + 2*PP2 + 4*PT2) - 20000
OT3 = (5*PL3 + 2*PP3 + 4*PT3) - 20000
prob += IL1 + IL2 + IL3 + IP1 + IP2 + IP3 + IT1 + IT2 + IT3 + 10 * (OT1 + OT2 + OT3)
# Solve the problem
prob.solve()
# print solve status
print("Status:", LpStatus[prob.status])
# Print optimum values
for v in prob.variables():
print(v.name, "=", v.varValue)
print("Total Costs = ", value(prob.objective))
print(OT1)
这给了我以下结果:
Status: Optimal
Prod_Laptop_February = 1000.0
Prod_Laptop_January = 50.0
Prod_Laptop_March = 1500.0
Prod_Phone_February = 2000.0
Prod_Phone_January = 1880.0
Prod_Phone_March = 2000.0
Prod_Tablet_February = 3000.0
Prod_Tablet_January = 1950.0
Prod_Tablet_March = 2000.0
Total Costs = -76900.0
5*Prod_Laptop_January + 2*Prod_Phone_January + 4*Prod_Tablet_January - 20000
我希望最后一行是一个整数值,但事实并非如此。有人可以向我解释如何将表达式转换为整数值吗?
答案 0 :(得分:2)
代码中的最后一个打印状态将打印PuLP表达式。由于它是非本地python对象,因此它的字符串表示由PuLP定义(在类中重载)。
在这种情况下,表达式本身以人类可读的形式呈现。
如果要访问它的值,只需将最后一行替换为:
print(OT1.value())