Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to interact with the previous variable in a for loop in Python?

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Two recommendations:

  1. Iterate over the dictionary using .items()
  2. Add logic guarding against trying to access a key in schedule that does not exist prior to calling schedule[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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading