Develop a greedy algorithm in Python to complete a given optimization task.
- User
Develop a greedy algorithm in Python to complete a given optimization task.
Assistant
Develop a greedy algorithm in Python to complete a given optimization task.
Problem: Develop a greedy algorithm in Python to complete a given optimization task.
Approach: because the local optimal choice (picking the activity that finishes earliest) leads to the global optimal solution (maximum number of activities).
Key considerations:
def greedy_activity_selector(start_times, finish_times): """ Solves the Activity Selection problem using a greedy approach.
Let me implement this solution.
Since the specific optimization task wasn't defined, I will select the classic Activity Selection Problem (also known as Interval Scheduling). This is one of the best illustrations of a greedy algorithm because the local optimal choice (picking the activity that finishes earliest) leads to the global optimal solution (maximum number of activities).
Problem Statement: You are given a set of activities with start times and finish times. You need to select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time.
Greedy Strategy: Always pick the activity with the earliest finish time that doesn't conflict with the previously selected activity. By finishing early, we leave the maximum amount of time remaining for other activities.
Here is the complete algorithm with detailed comments.
def greedy_activity_selector(start_times, finish_times):
"""
Solves the Activity Selection problem using a greedy approach.
Args:
start_times (list): A list of integers representing start times.
finish_times (list): A list of integers representing finish times.
Returns:
list: The indices of the selected activities.
"""
# 1. Combine start and finish times into a list of tuples and sort them.
# A greedy algorithm often requires sorting data based on a specific criteria.
# Here, we MUST sort by finish times.
activities = sorted(zip(start_times, finish_times), key=lambda x: x[1])
# Extract the sorted lists for easier processing
sorted_start = [act[0] for act in activities]
sorted_finish = [act[1] for act in activities]
n = len(activities)
selected_activities = []
# 2. Initialization
# The first activity in the sorted list always gets selected because it finishes first.
# This provide