【问题标题】:python pulp, if statement using pulp.variablespython纸浆,if语句使用纸浆.变量
【发布时间】:2018-03-16 23:54:34
【问题描述】:

最近,我在使用 Pulp 时遇到了一些问题。

我这样定义我的问题。

point = lp.LpProblem("Maximize the Points", lp.LpMaximize)
#the dict can only be string, so we use a list containing string
students = [str(i) for i in list(range(96))]
groups = [str(i) for i in list(range(24))]

choices = lp.LpVariable.dicts("Choice",(groups,students),0,1, cat = "Integer")

为了解决我的线性规划问题,我的目标非常复杂,我需要使用一些自己编写的函数来解决它。是这样的,

point +=  1 * cal_lang() \
        + 1 * cal_leader() \
        + 1 * cal_learn() \
        + 1 * cal_like() \
        - 10 * cal_dislike() , "Maximize the evaluation points"

同时,在cal_lang中,我需要计算多少个变量等于1所以我使用

if lp.value(choices[group][student]) == 1 :

但是,即使将pulp.value 定义为类似,这也不起作用。

纸浆值(x) 返回变量/表达式 x 的值,如果是数字则返回 x。

print('%%%%%%%%%%%%%%%%%')
print(choices["5"]["5"])
print(type(choices["5"]["5"]))
print(lp.value(choices["5"]["5"]))
print('%%%%%%%%%%%%%%%%%')

这太混乱了。然后我尝试提取变量的类型和值。代码和输出是这样的。

%%%%%%%%%%%%%%%%%
Choice_5_5
<class 'pulp.pulp.LpVariable'>
None
%%%%%%%%%%%%%%%%%

似乎我可以提取定义为整数 0 或 1 的变量 chioces["5"]["5"] 的值,而我的 "if" 不起作用。

我该如何解决这个问题?

【问题讨论】:

  • 毕竟很难遵循您的代码或您正在做的事情。您不能只使用任何外部运算符、if-else 或外部函数作用于模型内的变量(仿射形式除外)。如果你在对最终解决方案做某事之前使用varaible.value 或类似的东西,你可能做错了什么。因此,请尝试更准确地了解您在做什么,并尝试最小化/提取问题的核心
  • 在找到解决方案之前没有定义变量的值。我建议你看看例子

标签: linear-programming pulp


【解决方案1】:

我需要计算多少个变量等于1的个数

因为choices 是一个二进制变量。这非常简单:

 count = sum((i,j), choices(i,j))

(在类似数学的符号中)。这可以使用lpSum 直接在 Pulp 中转录。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    • 2020-09-16
    相关资源
    最近更新 更多