Finding (number of) overlaps in a list of time ranges

后端 未结 9 646
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 19:53

Given a list of time ranges, I need to find the maximum number of overlaps.

Following is a dataset showing a 10 minute interval of calls, from which I am trying to f

9条回答
  •  半阙折子戏
    2020-12-04 20:20

    This seems like a reduce operation. The analogy is that each time a call is started, the current number of active calls is increased by 1. Each time a call is ended, the current number of calls drops to zero.

    Once you have that stream of active calls all you need is to apply a max operation to them. Here is a working python2 example:

    from itertools import chain
    inp = ((123, 125),
           (123, 130),
           (123, 134),
           (130, 131),
           (130, 131),
           (130, 132),)
    
    # technical: tag each point as start or end of a call
    data = chain(*(((a, 'start'), (b, 'end')) for a, b in inp))
    
    def r(state, d):
        last = state[-1]
        # if a call is started we add one to the number of calls,
        # if it ends we reduce one
        current = (1 if d[1] == 'start' else -1)
        state.append(last + current)
        return state
    
    max_intersect = max(reduce(r, sorted(data), [0]))
    
    print max_intersect
    

提交回复
热议问题