简体   繁体   中英

how to be pythonic in a 2d nested for loop comprehension for pulp

I can't get over this hump in my program. I would like to reduce this repetitive code to a simpler code. To make short these are constraints for pulp.

I have 2 shift patterns: "Shift_Pattern_1" and "Shift_Pattern_Master"

Employees is a list with names inside.

 Days:["Monday", "Tuesday", "Wednesday", "Thursday", "Friday",    
 "Saturday", "Sunday"]

Shift_pattern_Master = ["Morning", "Mid", "Night"]
Shift_pattern_1 = ["Morning", "Night"]

Week1={"Monday":2, "Tuesday":2, "Wednesday":3, "Thursday":2, "Friday":2,    
"Saturday":3, "Sunday":2} # number a people needed a to day work.

for day in Days[0:2]: # Monday and Tuesday only
    for employee in Employees:
        prob += pulp.lpSum(avail[employee, day, shift] for shift in      
Shift_pattern_1)==requests[employee][day]

for day in Days[2:3]: #wednesday
    for employee in Employees:
        prob += pulp.lpSum(avail[employee, day, shift] for shift in     
 Shift_pattern_Master)==requests[employee][day]

 ....more code to finish the week.........

When i complete the entire code from above, I get 35 constraints.

my attempt was to use if and else to shorten the code and i only get 30 constraints. i know the problem is "if Week1[day]==2" because some constraints are missing.

  1. i don't know where to put that if statement, or
  2. is there a better way to be more pythonic?

    for day in Days: if Week1[day]==2: for employee in Employees: prob += pulp.lpSum(avail[employee, day, shift] for shift in
    Shift_pattern_1)==requests[employee][day] else:
    prob += pulp.lpSum(avail[employee, day, shift] for shift in Shift_pattern_Master)==requests[employee][day]

thanks in advance.

if the unique day is Wednesday you want to do:

for day in Days: 
   if day=="Wednesday": 
      for employee in Employees: 
          prob += pulp.lpSum(avail[employee, day, shift] for shift in Shift_pattern_1)==requests[employee][day] 
   else:
      for employee in Employees: 
          prob += pulp.lpSum(avail[employee, day, shift] for shift in Shift_pattern_Master)==requests[employee][day]

however, I think you actually want the above condition so you just need to include the employees loop

for day in Days: 
   if Week1[day]==2: 
      for employee in Employees: 
          prob += pulp.lpSum(avail[employee, day, shift] for shift in Shift_pattern_1)==requests[employee][day] 
   else:
      for employee in Employees: 
          prob += pulp.lpSum(avail[employee, day, shift] for shift in Shift_pattern_Master)==requests[employee][day]

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