I'm getting started with OR-TOOLS from Google and I couldn't figure out how to declare variables dynamically.
A very simple example in OR-TOOLS websites in given as follows
x = solver.NumVar(0, 10, 'x')
y = solver.NumVar(0, 10, 'y')
solver.Add(x + 7 * y <= 17.5)
solver.Maximize(x + 10 * y)`
Because I am modelling a Benders decomposition, I'm trying to declare some variables inside a loop. Thus, I could dynamically create its variables.
I've tried something like:
for i in range(3):
x[i] = solver.NumVar(0, 10, 'x[i]')
y[i] = solver.IntVar(0, 10, 'y[i]')
solver.Add(x[i] + 7 * y[i] <= 17.5)
However, that clearly doesn't work.
Could someone help me please? Thanks!
This approach surely works and is probably shown in lots of examples.
Without testing, your idea could look like:
# prepare some data-structure to hold variables returned
x = [None] * 3
y = [None] * 3
for i in range(3):
x[i] = solver.NumVar(0, 10, 'x[{}]'.format(i))
y[i] = solver.IntVar(0, 10, 'y[{}]'.format(i))
solver.Add(x[i] + 7 * y[i] <= 17.5) # invariant is important!
# we only access available indices
Nothing wrong with that conceptionally.
Your variables will now be ready to be used / consumed by access your lists.