built in function for computing overlap in Python

后端 未结 4 1339
囚心锁ツ
囚心锁ツ 2020-12-09 08:33

is there a built in function to compute the overlap between two discrete intervals, e.g. the overlap between [10, 15] and [20, 38]? In that case the overlap is 0. If it\'s

4条回答
  •  渐次进展
    2020-12-09 08:56

    You can use max and min:

    >>> def getOverlap(a, b):
    ...     return max(0, min(a[1], b[1]) - max(a[0], b[0]))
    
    >>> getOverlap([10, 25], [20, 38])
    5
    >>> getOverlap([10, 15], [20, 38])
    0
    

提交回复
热议问题