擅长:python、mysql、java
<p>在一维中,检查重叠的前提很简单(我认为)。找出<code>minimum</code>值中的较大值和<code>maximum</code>值中的较小值。然后减去两者。</p>
<pre><code>def overlap(min1, max1, min2, max2):
#Find out the bigger minimum
if min1 >= min2:
bigger_min = min1
else:
bigger_min = min2
if max1 >= max2:
smaller_max = max2
else:
smaller_max = max1
if smaller_max <= bigger_min:
return 0
else:
return smaller_max - bigger_min
</code></pre>
<p>结果</p>
<pre><code>>>> overlap(20,40,30,70)
10
>>> overlap(0,100,200,300)
0
>>> overlap(0,100,0,30)
30
>>> overlap(0,100,30,60)
30
>>> overlap(0,100,30,70)
40
>>> overlap(20,100,30,70)
40
>>> overlap(20,30,30,70)
0
>>> overlap(0,50,0,50)
50
</code></pre>