gpt4 book ai didi

python - 如何简化重复的 Python PuLP 语法?

转载 作者:太空狗 更新时间:2023-10-30 02:47:00 24 4
gpt4 key购买 nike

如何将以下 Python PuLP 语句简化为更 Pythonic、可管理和正确的东西:

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

最佳答案

列出年份而不是 100 年变量:

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

请注意,列表是从 0 开始索引的,所以以前的 year_1 现在是 years[0]

您可以在脚本的“声明约束”部分遍历它:

for year, next_year in zip(years[:-1], years[1:]):
prob += next_year - year >= 0

关于python - 如何简化重复的 Python PuLP 语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17754363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com