python - How do I generate PuLP variables and constrains without using exec? -


i have written following python code using pulp library solving knapsack problem using integer programming formulation. using strings generate lpvariable commands , add constraints , executing them eval. there way without using eval?

from pulp import *  #knapsack problem  items = input ('enter number of items :')  items = int(items)  #print('enter %d items 1 one')  print ('enter {0} items profit 1 one'.format(items))  obj = [] weight = [] knapweight = 0   in range(0,items):     print('enter {0} item profit : '.format(i+1))     obj.append(input())  in range(0, items):     print('the profit @ {0} {1}'.format(i, obj[i]))  print ('\nenter {0} items weights 1 one'.format(items))   in range(0, items):     print('enter {0} item weight'.format(i+1))     weight.append(input())  in range(0, items):     print('the profit @ {0} {1}'.format(i, weight[i]))  print ('\nenter weight of knapsack :') knapweight = input()  print ('the weight of knapsack : {0}'.format(knapweight))   #generating variables in range(0, items):     str = 'x{0} = lpvariable("x{1}", cat=\'binary\')'.format(i+1,i+1)     print (str)     exec(str)  prob = lpproblem('knapsack', lpmaximize)  print ('\ndynamic generaion\n')  #weight constraint generation str = "prob += "  in range(0, items):     if == (items-1):         str = str + weight[i] + '*x{0}'.format(i+1)     else:         str = str + weight[i] + '*x{0}'.format(i+1) + '+'  str = str + '<=' + knapweight exec(str) print(str)  #objective function generation str = "prob += "  in range(0, items):     if == (items-1):         str = str + obj[i] + '*x{0}'.format(i+1)     else:         str = str + obj[i] + '*x{0}'.format(i+1) + '+'  exec(str) print(str)  status = prob.solve() print(lpstatus[status])  print ('\nthe values of variables : \n')  in range(0, items):     print('x{0} = {1}'.format(i+1, value(eval('x{0}'.format(i+1))))) 

the key recognizing it's okay have object -- 1 in list or dictionary -- don't have explicitly bound name. can make object, append list, , ever refer some_list[2]. once allow freedom, code can become simpler.

here i've hardcoded inputs, because doesn't matter:

from pulp import *  objs = [2,3,2,5,3] weights = [1,2,2,1,3] knapweight = 5  prob = lpproblem('knapsack', lpmaximize) xs = [lpvariable("x{}".format(i+1), cat="binary") in range(len(objs))]  # add objective total_prof = sum(x * obj x,obj in zip(xs, objs)) prob += total_prof  # add constraint total_weight = sum(x * w x,w in zip(xs, weights)) prob += total_weight <= knapweight  status = prob.solve() print(lpstatus[status]) print("objective value:", value(prob.objective)) print ('\nthe values of variables : \n') v in prob.variables():     print(v.name, "=", v.varvalue) 

which gives me

optimal objective value: 10.0  values of variables :   x1 = 1.0 x2 = 1.0 x3 = 0.0 x4 = 1.0 x5 = 0.0 

here i'm building lpvariables in list comprehension

xs = [lpvariable("x{}".format(i+1), cat="binary") in range(len(objs))] 

where objects live in list xs.

>>> xs [x1, x2, x3, x4, x5] >>> xs[3] x4 >>> type(xs[3]) <class 'pulp.pulp.lpvariable'> 

Comments