Bắt đầu ngayBắt đầu miễn phí

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.

Bài tập này là một phần của khóa học

Introduction to Optimization in Python

Xem khóa học

Hướng dẫn bài tập

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

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

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}") 
Chỉnh sửa và Chạy Mã