我对其他答案的复杂性感到惊讶。这应该是:
def intersect(a, A, x, X):
'''Return True if any number in range(a, A+1) is in range(x, X+1).'''
return a <= X and x <= A
请注意,交集是对称的,所以intersect(a,b,x,y) == intersect(x,y,a,b) 始终成立。
所有交叉点的可能性:
a...A
x..X
a...A
x..X
a...A
x..X
a...A
x..X
a...A
x..X
a...A
x..X
a...A
x..X
a...A
x..X
对应上面的函数。
最后,确保这与 John Kugelman 的回答没有什么不同:
def their(a, b, x, y):
return ((x <= a <= y or x <= b <= y) or (a <= x <= b or a <= y <= b))
def my(a, A, x, X):
return a <= X and x <= A
from itertools import product
for x in product(range(5), repeat=4):
if my(*x) != their(*x):
if x[0] <= x[1] and x[2] <= x[3]:
print('[{1}, {2}] and [{3}, {4}] intersect according to {0}.'
.format('me' if my(*x) else 'them', *x))
else:
print('{} say it intersects, when input is incorrect.'
.format('I' if my(*x) else 'They'))
将其作为python intersect.py | uniq -c 输出运行:
140 They say it intersects, when input is incorrect.