I need a little help with a for loop in Python. At the moment, I am trying to create a random shift generator, but I also need to apply some rules on it. Right now, my function add shifts to a calendar randomly, but what I want is to add day off if the last shift was an evening shift. But I am not really sure how to interact with the previous 'i' variable in a for loop. Here is my code:
# Shift types
shifts = {
"morning": "9:00 - 17:00",
"evening": "16:00 - 00:00",
}
day_off = {
"day off": "X"
}
# Schedule
schedule_ll = {
1: [],
2: [],
3: [],
4: [],
5: [],
6: [],
7: [],
8: [],
9: [],
10: [],
11: [],
12: [],
13: [],
14: [],
15: [],
16: [],
17: [],
18: [],
19: [],
20: [],
21: [],
22: [],
23: [],
24: [],
25: [],
27: [],
28: [],
29: [],
30: [],
31: [],
}
# Function to add shifts to schedule randomly
def start_schedule(schedule, shift, day_off):
for i in schedule:
schedule[i].append(random.choice(list(shift.values())))
if schedule[i-1] == ["16:00 - 00:00"]:
schedule[i] = list(day_off.values())
return schedule
print(start_schedule(schedule_ll, shifts, day_off))
So when I execute this code, I receive KeyError: 0 error. I know that this error caused due to schedule[i-1], however I am not really sure how to make it work in other way. Will appreciate any help!
CodePudding user response:
You may want to treat the first element outside the loop, and then only loop over the remaining elements. Or even simpler, just change your if to
if i>1 and schedule[i-1] == ["16:00 - 00:00"]
As an aside, note that you may create your dictionary with a comprehension:
schedule = {k:[] for k in range(1,32)}
CodePudding user response:
Two recommendations:
- Iterate over the dictionary using
.items()
- Add logic guarding against trying to access a key in
schedule
that does not exist prior to callingschedule[i - 1]
This makes the code a bit cleaner, prevents the function from crashing on a key error, and checks that the desired condition holds for every day except the first day.
def start_schedule(schedule, shift, day_off):
for day, list_of_shifts in schedule.items():
list_of_shifts.append(random.choice(list(shift.values())))
if (i - 1) in schedule and schedule[i-1] == ["16:00 - 00:00"]:
schedule[i] = list(day_off.values())
return schedule