2016-10-11 244 views
1

我試圖打印一個變量的值,定義爲LpVariable(PuLP 1.6.1,Python 3.5)。 LpVariable可以選擇將參數的類別設置爲「整數」。但是,當我要求打印變量時,這不會導致數值。 在此一塊的問題,我試圖解決:Python,PuLP:將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 

最後一行我希望是一個整數值,但事實並非如此。有人可以向我解釋如何將表達式轉換爲整數值嗎?

回答

2

代碼中的最後一個打印狀態將打印一個PuLP表達式。由於它是一個非本地python對象,它的字符串表示是由PuLP定義的(在類中重載)。

在這種情況下,表達本身以人可讀形式呈現。

如果您要訪問它的價值,只是替換最後一行:

print(OT1.value()) 
+0

謝謝,沒有的伎倆! – Jeroen