Open essepuntato opened 6 months ago
def test_select_activities(set_of_activities, expected):
return select_activities(set_of_activities) == expected
def select_activities(set_of_activities):
most_productive = []
sorted_activites = sorted(list(set_of_activities), key=lambda tup: tup[1])
while sorted_activites:
activity = sorted_activites.pop(0)
if not most_productive:
most_productive.append(activity)
elif activity[0] > most_productive[-1][1]:
most_productive.append(activity)
return most_productive
activities = {(7, 8), (5, 8), (9, 11), (8, 10), (13, 15), (16, 18), (15, 18)}
activites2 = {(6, 7), (7, 9), (9, 11), (11, 13), (13, 15), (15, 18), (18, 20)}
print(test_select_activities(activities, [(5, 8), (9, 11), (13, 15), (16, 18)]))
print(test_select_activities(activites2, [(6, 7), (9, 11), (13, 15), (18, 20)]))
Suppose one has to address the maximum number of activities in a day, choosing them from a set of available activities, considering that one cannot handle more than one activity simultaneously. A tuple defines each activity. The first element specifies the starting time (a value from 0 to 24, indicating the starting hour). The second element represents the finish time (a value from 0 to 24, marking the ending hour). Develop the Python function
def select_activities(set_of_activities)
using a greedy approach. It takes in input a set of activities of a day and returns the list of the maximum number of non-overlapping activities one can address, ordered according to the starting time. Hint: think about the finish time of each activity and see how it may affect the selection. Accompany the implementation of the function with the appropriate test cases.