# import PuLP's functions
from pulp import *
# create new task of Linear programming (LP) with maximize of the goal functions
prob = LpProblem("Knapsack problem", LpMaximize)
# variable (integer)
x1 = LpVariable("x1", 0, 10, 'Integer')
x2 = LpVariable("x2", 0, 10, 'Integer')
x3 = LpVariable("x3", 0, 10, 'Integer')
# goal function ("the cost of all in backpack")
# create new task of Linear programming (LP) with maximize of the goal functions
prob = LpProblem("Knapsack problem", LpMaximize)
# variable (integer)
x1 = LpVariable("x1", 0, 10, 'Integer')
x2 = LpVariable("x2", 0, 10, 'Integer')
x3 = LpVariable("x3", 0, 10, 'Integer')
# goal function ("the cost of all in backpack")
prob += 17*x1 + 30*x2 + 75*x3, "obj"
# constraints ("weight of the backpack")
prob += 1.5*x1 + 2.5*x2 + 6*x3 <= 20, "c1"
# run solver
prob.solve()
# print task status
print "Status:", LpStatus[prob.status]
# print optimized variable result
for v in prob.variables():
print v.name, "=", v.varValue
# print value of goal function
print ("objective = %s$" % value(prob.objective))
Alternate:
we can create LP-file (CPLEX) and use it with GLPK:
# constraints ("weight of the backpack")
prob += 1.5*x1 + 2.5*x2 + 6*x3 <= 20, "c1"
# run solver
prob.solve()
# print task status
print "Status:", LpStatus[prob.status]
# print optimized variable result
for v in prob.variables():
print v.name, "=", v.varValue
# print value of goal function
print ("objective = %s$" % value(prob.objective))
Alternate:
we can create LP-file (CPLEX) and use it with GLPK:
cmd=['glpsol.exe','--cpxlp', outputname,'-o',solfile]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
for line in p.stdout:
print(">>>>> " + str(line.decode()).rstrip())
Комментариев нет:
Отправить комментарий