How do I create a variable where one index depends on the value of another index?

Peter Otten __peter__ at web.de
Tue Aug 7 13:30:09 EDT 2018


giannis.dafnomilis at gmail.com wrote:

> Hello guys. I'm having an issue with a Python PulP MILP problem. You can
> find the simplified code that reproduces the problem here:
> 
> from pulp import *
> machines = 2
> I = range(machines)
> positions = 2
> J = range(positions)
> years = 10
> T = range(years)
> age = {0: 5, 1: 7}
> 
> IR = 0.06
> df = 0.3
> 
> costs = {(0,0):300, (0,1):200, (1,0):500, (1,1):350}
> 
> factor = {}
> finalcosts = {}
> for i in I:
>     for j in J:
>         for t in T:
>             for k in range(age[i]):
>                 factor[t,k] = ((1-df)**k)/((1+IR)**t)
>                 finalcosts[i,j,t,k] = costs[i,j]*factor[t,k]
>                 
> prob = LpProblem("TrialProb",LpMinimize)
> 
> Prob_vars = LpVariable.dicts("probvars", ((Machine, Position,Year, Age)
> for Machine in I for Position in J for Year in T for Age in
> range(age[i])),0,None, LpInteger)

That should probably be age[Machine], not age[i] in the line above.

> This gives me a 'finalcosts' variable with a size of 240 which is what I
> want, with all the correct values. But the 'Prob_vars' are of a size 260,
> counting the second index k for the first index i as well. Meaning that
> while in 'finalcosts' for i=0, k=0:4 and for i=2, k=0:6 (which is what I
> want), for the 'Prob_vars' decision variable index k=0:6 for both i=1 &
> i=2.
> 
> I'm fairly new to Python so I can't quite grasp where the problem lies.
> 
> What I have tried:
> 
> I've tried all combinations that I could think of for different
> expressions of the 'Prob_vars' but nothing works properly. I also looked
> anywhere I could think of online but I can't find an answer to this.





More information about the Python-list mailing list