給定由起始點和終點(兩個浮點數)定義的間隔,我想確定第二個間隔的交集範圍。例如:獲取兩個非離散間隔的交集範圍
int1 = [2. , 5.]
int2 = [2.2, 7.]
>>> desired_function(int1, int2)
2.8
應該處理所有交叉點的可能性(沒有交點,部分相交,相交完成,也爲負的範圍等)。我的嘗試是這樣的:
def intersection(int1, int2):
#case 1: partial intersection over the left or right border
if (int2[0]<=int1[0] and int2[1]<=int1[1]) or (int2[0]>=int1[0] and int2[1]>=int1[1]):
return min(int1[1],int2[1]) - max(int1[0],int2[0])
#case 2: complete overlap of one interval by the other
elif (int2[0]>=int1[0] and int2[1]<=int1[1]) or (int2[0]<=int1[0] and int2[1]>=int1[1]):
return min (int2[1]-int2[0] , int1[1]-int1[0])
#case 3: no overlap at all
else:
return 0
問:我錯過了一些東西,在那裏,做類似的,因爲要保持我的代碼一樣簡單和儘快任何東西積聚在溶液中或包裝?
謝謝!這實際上正是我的第一種情況的「return」聲明,但是我以某種方式試圖努力並且沒有意識到這已經處理了所有可能性......'+ 1'用於多個間隔的解決方案 –