简体   繁体   中英

python pulp not matching value of variable dict

I am struggling to simplify the constraint for a few days now. still learning python. please help and thank you in advance.

    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]]

as an example, the first few constraints:

"_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" is just so happened to be the SUM of all the 1's and the 0's in my nested dict.)

Instead i like to have each variable matching 1's and 0's from my nested dict.

"_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"

After the == sign you want the value 1 or 0 from the dictionary, therefore you should use:

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

With requests[employee] you select the dictionary for that employee

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

Then by adding [day] you select the day from that dictionary:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM