Search code examples
pythonlinear-programmingpulp

Pulp: Adding multiple LpSum in a loop


I have a list like:

list = [var_1, var_2, var_3]

Using Pulp library, I'm trying to define them as variables with a for loop doing:

LpVariable(list[i] for i in range(len(list)))

Then I'm trying to sum them all and asign it to the model:

model += LpVariable(list[i] for i in range(len(list)))

In both cases I'm getting an error that says expected string or bytes-like object

Can anyone help me?

Regards


Solution

  • Id did not check the syntax but lpSum can sum a list of LpVariables so do you want something that looks more like

    model += LpSum([LpVariable(i) for i in list])
    

    this assumes that the elements of your list are name strings and you want to create new LpVariables.

    if so, you may want to first save these new LpVariables in a list or dict so you can use them in constraints and then add them as a objective to the model

    if the elements of your list are already LpVariables then you just need

    model += LpSum(list)