Get startedGet started for free

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.

This exercise is part of the course

Introduction to Optimization in Python

View Course

Exercise instructions

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

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

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}") 
Edit and Run Code