I am trying to create a schedule function that uses only python built-in modules that will return the maximum number of non overlapping appointments. The function's input is a list of lists, the inner list contains 2 integer elements, the start and end time. The start and end times cannot be changed and if the start time of one meeting is the same as the end time of another, they are not considered overlapping. For example:
Input:
meetings = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5]]
max_meetings(meetings)
Output:
4
The Code I have now just brute forces it and is wildly inefficient in both memory and execution time. Even though it's fun to use classes, it seems like there would be a better way to do it.
def max_meetings(meetings):
'''
Return the maximum number of non overlapping meeting that I can attend
input:
meetings - A list of lists. the inner list contains 2 values, the start
time[0] and the end time[1].
returns:
total - The total number of non overlapping meetings that I can attend.
'''
num_meetings = len(meetings)
assert (num_meetings <= 100)
appt_obj = [Appt(o) for o in meetings]
total = 0
for appt in appt_obj:
schedule = Schedule()
schedule.add_meeting(appt)
counter = 0
for comp_appt in appt_obj:
counter += 1
schedule.add_meeting(comp_appt)
# If there isnt a chance, break to save some time
if ((num_meetings - counter) < (total - schedule.meetings)):
break
if schedule.meetings > total:
total = schedule.meetings
return total
class Schedule:
'''
A class to hold my entire schedule. Can add
appointments
'''
def __init__(self):
self.times = set()
self.meetings = 0
def add_meeting(self, appt):
points = range(appt.start, appt.end)
if any(x in self.times for x in points):
pass
else:
# This for loop also seems unnecessary
for p in points:
self.times.add(p)
self.meetings += 1
class Appt:
'''
A class for an appointment
'''
def __init__(self, meeting):
assert (meeting[0] >= 0)
assert (meeting[1] <= 1000000)
self.start = meeting[0]
self.end = meeting[1]