Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Introduction to Optimization in Python

Cursus bekijken

Oefeninstructies

  • Adjust the variable definition to use LpVariable.dicts(), saving them as variables with the name "Food".
  • Adjust the objective function to use lpSum().

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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}") 
Code bewerken en uitvoeren