Let set up our problem with the decision variables (items), with their value “v” and weight “w”. We then set up the capacity of our bagpack.
# A list of tuples of items (value, weight)# (value, volume)items = [(3,4), (8,5), (10,1.5), (2,0.5), (7,1), (10,2), (5,1.5), (9,1), (9,0.5), (6,0.5)]# number of itemsitemCount =len(items)# Knapsack max weight capacitybinCapacity =7
Here we set up our decision variables (the X), the lower and upper bounds, couple with the integer constrains (cat=Integer) tells us the decision variable will be binary.
# Decision variables (array), x[i] gets 1 when item i is included in the solutionx = pulp.LpVariable.dicts('item', range(itemCount), lowBound =0, upBound =1, cat ='Integer')
Here we set up our problem (it is of maximization type, and it is a linear programming problem).
We add the objective function (sum of the values), and the constraint (sum of the weights).
# Initialize the problem and specify the typeproblem = LpProblem("Knapsack Problem", LpMaximize)# Add the objective functionproblem += lpSum([ x[i] * (items[i])[0] for i inrange(itemCount) ]), "Objective: Maximize profit"# Capacity constraint: the sum of the weights must be less than the capacityproblem += lpSum([ x[i] * (items[i])[1] for i inrange(itemCount) ]) <= binCapacity, "Constraint: Max capacity"
Here we write the problem as an lp file and we then solve it, using the “solve” function. We also keep track of the time it takes.
#print problem.constraints# Write the model to disk, not necessaryproblem.writeLP("Knapsack.lp")# Solve the optimization problemstart_time = time.time()problem.solve()print("Solved in %s seconds."% (time.time() - start_time))
Solved in 0.011299371719360352 seconds.
Finally, we report on the optimal solution, and whether each variable was chosen or not
# Was the problem solved to optimality?print("Status:", LpStatus[problem.status])# Each of the variables is printed with it's resolved optimum valuefor v in problem.variables():print(v.name, "=", v.varValue)# The optimised objective function value is printed to the screenprint("Total profit = ", value(problem.objective))