类似于What's the most efficient way to test two integer ranges for overlap?的问题,但更为高级:
让我们给定两个包含整数的范围[x1:x2]和[y1:y2],其中x1≤x2和y1≤y2。
x1和/或y1可以是整数或负无穷大(表示为None
Python对象),x2和/或y2可以是整数或正无穷大(表示为None
Python对象)
测试两个范围是否存在重叠的最佳方法是什么?
我确定我可以编写算法,但是也许您会为我找到一个较短的Python代码?
(实际上,我处理的不是整数,而是“ 3.7”之类的版本字符串。但是我认为我自己从整数转换为版本字符串不会有任何麻烦。)
答案 0 :(得分:1)
我认为应该这样做,只是检查const removeItem = (arr, i) => {
return arr.slice(0, i).concat(arr.slice(i+1));
}
const makePermutations = (strArr) => {
const doPermutation = (strArr, pairArr) => {
return strArr.reduce((result, permutItem, i) => {
const currentPair = removeItem(pairArr, i);
const tempResult = currentPair.map((item) => permutItem+item);
return tempResult.length === 1 ? result.concat(tempResult) :
result.concat(doPermutation(tempResult, currentPair));
}, []);
}
return strArr.length === 1 ? strArr :
doPermutation(strArr, strArr);
}
makePermutations(["a", "b", "c", "d"]);
//result: ["abcd", "abdc", "acbd", "acdb", "adbc", "adcb", "bacd", "badc", "bcad", "bcda", "bdac", "bdca", "cabd", "cadb", "cbad", "cbda", "cdab", "cdba", "dabc", "dacb", "dbac", "dbca", "dcab", "dcba"]
之间可能存在的不同关系。可能可以用较短的形式编写,但是此代码强调了不同的情况。
x1, x2, y1, y2
还有一个更优雅的解决方案-
def checkIntersection(x1, x2, y1, y2):
if x1 is not None:
if y1 is not None:
if x1 <= y1 and (x2 is None or x2 > y1):
return True
elif y1 <= x1 and (y2 is none or y2 > x1):
return True
else:
return False
else:
if y1 is None:
return True
else:
if x2 is None or x2 > y1:
return True
return False