Asked • 07/12/19

Calculating the overlap distance of two 1D line segments?

Trying to build a function that will return the total overlapping distance between 2 line segments, denoted by start and end ints. Currently I have this: That I got off the internet somewhere,  def overlap(min1, max1, min2, max2):   """returns the overlap between two lines that are 1D"""   result = None   if min1 >= max2 or min2 >= max1: result = 0   elif min1 <= min2:    result = max1 - min2   else: result = max2 - min1   return result This works however for the case of 0 100, 0,20 it returns 100. And that's clearly wrong. Is there a simple way of calculating this that will return the correct values?

1 Expert Answer

By:

Michael H. answered • 07/13/19

Tutor
5 (184)

In-depth knowledge combined with clunky use of technology!

Michael H.

Of course, if you don't have a "smaller of" operation in Python, you can indeed do this with comparisons, thus: if max2 <= max1 then let b = max2 else b = max1 if min2 >= min1 then let a = min2 else a = min1 result = b - a
Report

07/13/19

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.