Question

How can I simplify the following Python PuLP statements into something more Pythonic, manageable and correct:

import pulp as lp

#delare variables
#Note that I have to model a 100 year period!
year_1 = lp.LpVariable("2011", 0, None, lp.LpInteger)    
year_2 = lp.LpVariable("2012", 0, None, lp.LpInteger)
year_. = lp.LpVariable("201.", 0, None, lp.LpInteger)
year_n = lp.LpVariable("201n", 0, None, lp.LpInteger)

#declare constraints
prob += year_1 - year_0 >= 0
prob += year_2 - year_1 >= 0
prob += year_. - year_. >= 0
prob += year_n - year_n_1 >= 0
Was it helpful?

Solution

Make a list of years instead of 100 year variables:

years = [lp.LpVariable(str(2011+i), 0, None, lp.LpInteger) for i in xrange(n)]

Note that lists are 0-indexed, so what used to be year_1 is now years[0].

You can loop over it for the "declare constraints" part of the script:

for year, next_year in zip(years[:-1], years[1:]):
    prob += next_year - year >= 0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top