MulaiMulai sekarang secara gratis

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.

Latihan ini adalah bagian dari kursus

Introduction to Optimization in Python

Lihat Kursus

Petunjuk latihan

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

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

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 dan Jalankan Kode