Question

# write a python program that include a function named activity_selection() and take in two arguments, first...

write a python program that include a function named activity_selection() and take in two arguments, first one would be the number of tasks and the second argument would be a list of activities. Each activity would have an activity number, start time and finish time.

Example activity_selection input and output:

activity_selection (11, [[1, 1, 4 ], [2, 3, 5], [3, 0, 6], [4, 5, 7], [5, 3, 9], [6, 5, 9],[7, 6, 10], [ 8, 8, 11], [ 9, 8, 12], [10, 2, 14], [11, 12, 16] ]

In the above example the first activity set contains 11 activities with activity 1 starting at time 1 and finishing at time 4, activity 2 starting at time 3 and finishing at time 5, etc. The activities are not in any sorted order. Your results including the number of activities selected and their order should be outputted to the terminal. For the above example the results are: Number of activities selected = 4 Activities: 2 4 9 11

Note: There can be multiple optimal solutions.

SOLUTION-

I have solved the python code below with comments for easy understanding and given screenshot also :)

CODE-

some note-

sort the list according to their finish time
Select the first activity from the sorted list and append the activity name in res.
Do following for remaining activities in the sorted list. If the start time of this activity is greater than or equal to the finish.time of previously selected activity then select this activity and append activity name in res.

code-

#program
def activity_selection(n,activity_list):
res=[]
activity_list.sort(key=lambda activity_list:activity_list[2])#sort according finish time
#print(activity_list)
res.append(activity_list[0][0])
i=0
count=1
#using the greedy approach
for j in range(1,n):

# If this activity has start time greater than or equal to the finish time of previously selected activity
# then select it
if activity_list[j][1] >= activity_list[i][2]:
res.append(activity_list[j][0])
i = j
count+=1
print("selected",count)   #print the count value
print("Activities",res)   #print the activities

activity_selection (11, [[1, 1, 4 ], [2, 3, 5], [3, 0, 6],
[4, 5, 7], [5, 3, 9], [6, 5, 9],
[7, 6, 10], [ 8, 8, 11],[ 9, 8, 12],
[10, 2, 14], [11, 12, 16] ])

SCREENSHOT-

IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I WILL SOLVE IT FOR YOU:)

#### Earn Coins

Coins can be redeemed for fabulous gifts.