Это пример проблемы «рюкзака» - когда вы хотите выбрать наиболее ценные предметы с учетом ограничения на количество / стоимость, которые могут быть выбраны.
Следующее:
from pulp import *
# PROBLEM DATA:
costs = [15, 25, 35, 40, 45, 55]
profits = [1.7, 2, 2.4, 3.2, 5.6, 6.2]
max_cost = 169
max_to_pick = 4
# DECLARE PROBLEM OBJECT:
prob = LpProblem("Mixed Problem", LpMaximize)
# VARIABLES
# x_i - whether to include item i (1), or not (0)
n = len(costs)
N = range(n)
x = LpVariable.dicts('x', N, cat="Binary")
# OBJECTIVE
prob += lpSum([profits[i]*x[i] for i in N])
# CONSTRAINTS
prob += lpSum([x[i] for i in N]) <= max_to_pick # Limit number to include
prob += lpSum([x[i]*costs[i] for i in N]) <= max_cost # Limit max. cost
# SOLVE & PRINT RESULTS
prob.solve()
print(LpStatus[prob.status])
print('Profit = ' + str(value(prob.objective)))
print('Cost = ' + str(sum([x[i].varValue*costs[i] for i in N])))
for v in prob.variables ():
print (v.name, "=", v.varValue)
Возвращает:
Optimal
Profit = 17.0
Cost = 165.0
('x_0', '=', 0.0)
('x_1', '=', 1.0)
('x_2', '=', 0.0)
('x_3', '=', 1.0)
('x_4', '=', 1.0)
('x_5', '=', 1.0)