Program to find in which interval how many tasks are worked on in Python

PythonServer Side ProgrammingProgramming

Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a list of intervals where each interval is like [start, end) and we also have a list of strings called types. Now for a given i, the intervals[i] shows the times someone worked on the job types[i] from [start, end). Two intervals of the same type never overlap or touch. So we have to find a sorted merged list where each item has [start, end, num_types], indicates from start to end, num_types number of tasks were being worked on.

So, if the input is like intervals = [ [0, 3], [5, 7], [0, 7] ] types = ["problem solving", "news","game play"], then the output will be [[0, 3, 2], [3, 5, 1],[5, 7, 2]], as we have these few types of work being done: Between [0, 3) "problem solving" and "game play", between [3, 5) "game play", and between [5, 7) "news" and "game play".

To solve this, we will follow these steps −

• ev := a new list

• for each interval start end pair (s, e) in intervals, do

• insert (s, 1) at the end of ev

• insert (e, −1) at the end of ev

• sort the list ev

• cnt := 0, last := −1

• ans := a new list

• for each time and increment parameter of events (t, inc) in ev, do

• if t is not same as last and cnt is not same as 0, then

• cnt := cnt + inc

• last := t

• return ans

Let us see the following implementation to get better understanding −

Example

Live Demo

class Solution:
def solve(self, intervals, jobs):
ev = []
for s, e in intervals:
ev.append((s, 1))
ev.append((e, −1))
ev.sort()
cnt = 0
last = −1
ans = []
for t, inc in ev:
if t != last and cnt != 0:
ans.append([last, t, cnt])
cnt += inc
last = t
return ans
ob = Solution()
intervals = [
[0, 3],
[5, 7],
[0, 7]
]
types = ["problem solving", "news", "game play"]
print(ob.solve(intervals, types))

Input

[[0, 3],[5, 7],[0, 7]], ["problem solving", "news", "game play"]

Output

[[0, 3, 2], [3, 5, 1], [5, 7, 2]]
Updated on 21-Oct-2020 10:36:40

Advertisements