python pulp不匹配变量dict的值

时间:2018-04-10 08:17:33

标签: python pulp

我现在正努力简化约束几天。还在学习python。请提前帮助并谢谢。

    Employees=['Paul', 'Ben', 'Nasim', 'Ceci', 'Victoria',]
    Days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',      
    'Saturday', 'Sunday']

    avail = pulp.LpVariable.dicts("on_off", ((employee, day) for     
    employee in Employees for day in Days), cat="Binary")

    requests={"Paul": {"Monday":1, "Tuesday":1, "Wednesday":1,   
    "Thursday":1, "Friday":1, "Saturday":1, "Sunday":1},
    "Ben": {"Monday":1, "Tuesday":1, "Wednesday":1, "Thursday":1, 
    "Friday":1, "Saturday":1, "Sunday":0},
    "Nasim": {"Monday":1, "Tuesday":1, "Wednesday":1, "Thursday":1, 
    "Friday":1, "Saturday":1, "Sunday":1},
    "Ceci": {"Monday":1, "Tuesday":1, "Wednesday":1, "Thursday":1, 
    "Friday":1,"Saturday":1, "Sunday":0},
    "Victoria": {"Monday":1, "Tuesday":1, "Wednesday":0, "Thursday":0, 
    "Friday":0, "Saturday":0, "Sunday":0}}



    for employee, day in avail:
            prob += avail[employee, day] == [requests[i][j] for i in    
            requests for j in requests[i]]

作为一个例子,前几个约束:

"_C13: on_off_('Paul',_'Monday') = 28
_C14: on_off_('Paul',_'Tuesday') = 28
_C15: on_off_('Paul',_'Wednesday') = 28
_C16: on_off_('Paul',_'Thursday') = 28
_C17: on_off_('Paul',_'Friday') = 28
_C18: on_off_('Paul',_'Saturday') = 28" 

(" 28"恰好是我所有1&#39的和,以及我的嵌套字典中的0&#39。)

相反,我希望每个变量都与我的嵌套字典中的1' s和0&#39匹配。

"_C13: on_off_('Paul',_'Monday') = 1
_C14: on_off_('Paul',_'Tuesday') = 1
_C15: on_off_('Paul',_'Wednesday') = 1
_C16: on_off_('Paul',_'Thursday') = 1
_C17: on_off_('Paul',_'Friday') = 1
_C18: on_off_('Paul',_'Saturday') = 1"

1 个答案:

答案 0 :(得分:0)

在==符号之后,您希望字典中的值为1或0,因此您应该使用:

for employee, day in avail:
    prob += avail[employee, day] == requests[employee][day]

通过请求[employee],您可以选择该员工的字典

requests['Paul'] = {"Monday":1, "Tuesday":1, "Wednesday":1,   
"Thursday":1, "Friday":1, "Saturday":1, "Sunday":1}

然后通过添加[day],从该词典中选择日期:

 requests['Paul']['Monday'] = 1