I have a Pulp problem that is working fine and gives me the right values, but I want to clean up the code. Here is the part in question:
prob += (select_vars['MeatA'] + select_vars['MeatB'] + select_vars['MeatC']) >= 3, ""
I want to put this into a for loop, like this:
meat_count = 0
Meats = ["MeatA", "MeatB", "MeatC"]
for i in Meats:
if select_vars[i] is not None: meat_count += 1
prob += meat_count >= 5, "Meat min"
But that is putting NoneTypes into my prob.variables() and I'm not sure why. There are no NoneTypes in my prob.variables() when I run it the first way without the for loop.
# Print out the variables with their optimal value
for v in prob.variables():
print("some none ", v)
if v.varValue > 0:
print(v.name, "=", v.varValue)
First of all, I recommend you check the Case Studies in the PuLP documentation. There, you will see how to use loops to make general models that adapt to your data. Also: I'm not sure you're making a difference between python variables and PuLP variables, which is important.
In your case, you probably want to do something like the following:
import pulp
prob = pulp.LpProblem('example')
Meats = ['MeatA', 'MeatB', 'MeatC']
select_vars = pulp.LpVariable.dicts("selected_vars", Meats)
prob += pulp.lpSum(select_vars.get(m, 0) for m in Meats) >= 3, ""
But I insist, check the examples to see what each constraint does.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.