我已经设置了以下 LP 问题,除了我对沙拉蔬菜的质量约束百分比之外,一切似乎都在工作。我希望沙拉蔬菜的质量至少为 40%,但纸浆的语法错误lpSum
,我不知道如何调和它。
我对每种沙拉都有以下限制:
至少 15 克蛋白质
至少 2 克,最多 8 克脂肪
至少 4 克碳水化合物
最多 200 毫克钠
至少 40% 的绿叶蔬菜(按质量计算)。
from pulp import *
# Creates a list of the Ingredients
Ingredients = ['TOMATO', 'LETTUCE', 'SPINACH', 'CARROT', 'SUNFLOWER', 'TOFU', 'CHICKPEAS', 'OIL']
kcal = {'TOMATO': 21,
'LETTUCE': 16,
'SPINACH': 40,
'CARROT': 41,
'SUNFLOWER': 585,
'TOFU': 120,
'CHICKPEAS': 164,
'OIL': 884}
protein = {'TOMATO': 0.85,
'LETTUCE': 1.62,
'SPINACH': 2.86,
'CARROT': 0.93,
'SUNFLOWER': 23.4,
'TOFU': 16,
'CHICKPEAS': 9,
'OIL': 0}
fat = {'TOMATO': 0.33,
'LETTUCE': 0.20,
'SPINACH': 0.39,
'CARROT': 0.24,
'SUNFLOWER': 48.7,
'TOFU': 5.0,
'CHICKPEAS': 2.6,
'OIL': 100.0}
carbs = {'TOMATO': 4.64,
'LETTUCE': 2.37,
'SPINACH': 3.63,
'CARROT': 9.58,
'SUNFLOWER': 15.0,
'TOFU': 3.0,
'CHICKPEAS': 27.0,
'OIL': 0.0}
sodium = {'TOMATO': 9.0,
'LETTUCE': 28.0,
'SPINACH': 65.0,
'CARROT': 69.0,
'SUNFLOWER': 3.80,
'TOFU': 120.0,
'CHICKPEAS': 78.0,
'OIL': 0.0}
cost = {'TOMATO': 1.0,
'LETTUCE': 0.75,
'SPINACH': 0.50,
'CARROT': 0.50,
'SUNFLOWER': 0.45,
'TOFU': 2.15,
'CHICKPEAS': 0.95,
'OIL': 2.00}
# Create the 'prob' variable to contain the problem data
prob = LpProblem("The Salad Problem", LpMinimize)
# A dictionary called 'ingredient_vars' is created to contain the referenced Variables
ingredient_vars = LpVariable.dicts("Ingr",Ingredients,0)
# The objective function is added to 'prob' first
prob += lpSum([kcal[i]*ingredient_vars[i] for i in Ingredients]), "Total kCal of Ingredients per salad"
# The constraints are added to 'prob'
prob += lpSum([protein[i] * ingredient_vars[i] for i in Ingredients]) >= 15.0, "ProteinRequirement"
prob += 8.0 >= lpSum([fat[i] * ingredient_vars[i] for i in Ingredients]) >= 2.0, "FatRequirement"
prob += lpSum([carbs[i] * ingredient_vars[i] for i in Ingredients]) >= 4.0, "CarbRequirement"
prob += lpSum([sodium[i] * ingredient_vars[i] for i in Ingredients]) <= 200.0, "SodiumRequirement"
prob += lpSum(prob.variables()[2].varValue + prob.variables()[4].varValue) / lpSum([prob.variables()[i].varValue for i in range(8)]) >= 0.40, "GreensRequirement"
prob.solve()
# The status of the solution is printed to the screen
print("Status:", LpStatus[prob.status])
# Each of the variables is printed with it's resolved optimum value
for v in prob.variables():
print(v.name, "=", v.varValue)
# The optimised objective function value is printed to the screen
print("Total kCal of Ingredients per salad = ", value(prob.objective))
这是给我问题的约束:
prob += lpSum(prob.variables()[2].varValue + prob.variables()[4].varValue) / lpSum([prob.variables()[i].varValue for i in range(8)]) >= 0.40, "GreensRequirement"
这会在 NoneType 上使用 + 运算符时出错,因为变量还没有值。我只是不确定如何设置这种约束。我已经查看了有关此的纸浆文档,但我没有任何运气来解决这个问题。