I need to solve a Linear Programming problem in python and came across PuLP. However I am having some doubts on how I can, in a simple manner, solve a problem with a varying number of inputs.

I have the following arrays, all with same dimensions:
a = [a0,a1,...,an] (the unknown variables)

u = [u0,u1,...,un]
v = [v0,v1,...,vn]
(these values are known)

and I want to maximize: a0*u0+a1*u1+...+an*un
subject to:

I can do this with a limited number of variables (3 for example):

prob = LpProblem("Decision",LpMaximize)

a = list()
a.append(pulp.LpVariable("a0", 0, 1))
a.append(pulp.LpVariable("a1", 0, 1))
a.append(pulp.LpVariable("a2", 0, 1))
u = np.array([1, 3, 2])
v = np.array([1, -1, 0])

prob += a[0]*u[0] + a[1]*u[1] + a[2]*u[2], "Expected Utility"

prob += a[0]+a[1]+a[2] == 1, "PercentagesSum"
prob += a[0]*v[0] + a[1]*v[1] + a[2]*v[2] >= 0, "MinimalOutcome"

However I want to be able to have a dynamic number of u.v., I think the solution might be in using LpVariable.dicts() but I had no success with it.

1 Answers

sascha On

If your variables are set up like you did, as variable-objects within a list (with n=len(mylist), it's pretty natural to use something like (list comprehension):

prob += lpSum([a[i] * u[i] for i in range(n)]), "Expected Utility"

The same goes for the other components. Of course you could also hold your variables in a dictionary and follow dict-like access.

The core-idea is just to use python's capabilities to collect your data and pulp's lpSum to sum it up.