Finding an integer distance between two intervals

I am 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] will be 2. If both intervals overlap in any way, the distance will be 0.

Any suggestions on an easy way to do this? I cannot help but think that there should be a clean, "pythonic" way to resolve this issue.

+4
source share
3 answers
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 
+5
source
 dist=min(y)-max(x) if dist>0: return dist else: return 0 
0
source

Hope the following helps:

 def myDist(a,b): if a[0] <= a[1] < b[0]: return b[0] - a[1] if b[0] <= b[1] < a[0]: return a[0] - b[1] return 0 

Good luck !!!

0
source

Source: https://habr.com/ru/post/1483649/


All Articles