Skip to content

Commit 5a0946e

Browse files
committed
Added activity selection problem implementation and its tests
1 parent 529d41c commit 5a0946e

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""
2+
Author: OMKAR PATHAK
3+
Created On: 26th August 2017
4+
"""
5+
6+
import inspect
7+
8+
def activity_selection(start_times, finish_times):
9+
"""
10+
:param start_times: An array that contains start time of all activities
11+
:param finish_times: An array that conatins finish time of all activities
12+
"""
13+
14+
if type(start_times) is not list:
15+
raise TypeError("Activity selection problem only accepts lists, not {}".format(str(type(start_times))))
16+
17+
if type(finish_times) is not list:
18+
raise TypeError("Activity selection problem only accepts lists, not {}".format(str(type(finish_times))))
19+
20+
if len(start_times) != len(finish_times):
21+
raise ValueError('Length of start_times list and finish_times list must be same')
22+
23+
n = len(start_times)
24+
activity = []
25+
26+
# first activity is also selected
27+
i = 0
28+
activity.append(i)
29+
30+
for j in range(n):
31+
# If this activity has start time greater than
32+
# or equal to the finish time of previously
33+
# selected activity, then select it
34+
if start_times[j] >= finish_times[i]:
35+
activity.append(j)
36+
i = j
37+
38+
return activity
39+
40+
def get_code():
41+
"""
42+
returns the code for the activity_selection function
43+
"""
44+
return inspect.getsource(activity_selection)

tests/test_greedy_algorithm.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from pygorithm.greedy_algorithm import (
55
fractional_knapsack,
6+
activity_selection,
67
)
78

89

@@ -13,5 +14,12 @@ def test_fractional_knapsack(self):
1314
W = 50
1415
self.assertEqual(fractional_knapsack.knapsack(W, value, weight), 240)
1516

17+
class TestActivitySelectionProblem(unittest.TestCase):
18+
def test_activity_selection(self):
19+
start_times = [1 , 3 , 0 , 5 , 8 , 5]
20+
finish_times = [2 , 4 , 6 , 7 , 9 , 9]
21+
22+
self.assertEqual(activity_selection.activity_selection(start_times, finish_times), [0, 1, 3, 4])
23+
1624
if __name__ == '__main__':
1725
unittest.main()

0 commit comments

Comments
 (0)