Handling multiple elements
The farmer wants to replicate the previous optimization function to detail with more complicated meals for other animals on the farm.
The previous code has been provided. Can you adjust the previous code to make it better at handling multiple variables?
pulp
has been imported for you.
Diese Übung ist Teil des Kurses
Introduction to Optimization in Python
Anleitung zur Übung
- Adjust the variable definition to use
LpVariable.dicts()
, saving them asvariables
with the name"Food"
. - Adjust the objective function to use
lpSum()
.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
model = LpProblem("MinCost", LpMinimize)
# Adjust the variable definition
C = LpVariable("C", lowBound=0)
S = LpVariable("S", lowBound=0)
# Adjust the objective function
cost = {'C': 0.11, 'S': 0.28}
model += 0.28*S + 0.11*C
model += 40*variables['S'] + 10*variables['C'] >= 17*(variables['C']+variables['S']), "M_protein"
model += variables['S'] + 2.5*variables['C'] >= 2*(variables['C']+variables['S']), "M_fat"
model += variables['C'] + variables['S'] >= 7, "M_weight"
model.solve()
print(f"Cost = {value(model.objective):.2f}")
print(f"Pounds of soybean = {variables['S'].varValue:.2f}, pounds of corn = {variables['C'].varValue:.2f}")