Search code examples
pythonintegerintervals

Finding integer distance between two intervals


I'm looking for an easy way to find the minimum distance between two integer intervals using python. For example, the minimum between [0,10] and [12,20] would be 2. If the two intervals overlap in any way, the distance would be 0.

Any suggestions on an easy way to do this? I can't help but think there must be a clean, 'pythonic' way to get at this question.


Solution

  • def solve(r1, r2):
         # sort the two ranges such that the range with smaller first element
         # is assigned to x and the bigger one is assigned to y
         x, y = sorted((r1, r2))
    
         #now if x[1] lies between x[0] and y[0](x[1] != y[0] but can be equal to x[0])
         #then the ranges are not overlapping and return the differnce of y[0] and x[1]
         #otherwise return 0 
         if x[0] <= x[1] < y[0] and all( y[0] <= y[1] for y in (r1,r2)):
            return y[0] - x[1]
         return 0
    ... 
    >>> solve([0,10],[12,20])
    2
    >>> solve([5,10],[1,5])
    0
    >>> solve([5,10],[1,4])
    1