当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Checking whether a bunch of intervals are overlapping

问题描述:

I don't know what to search for... What is a nice way to check whether a bunch of intervals are not overlapping?

Everything is fine:

a, b = 0.2, 0.3

c, d = 0.4, 0.6

e, f = 0.9, 1.0

Not good:

a, b = 0.2, 0.3

c, d = 0.25, 0.5

Evil²:

a, b = 0.2, 0.3

c, d = 0.4, 0.6

e, f = 0.1, 0.8

网友答案:

Sort the intervals by start value (if they're just 2-tuples this is automatic) and iterate through the list, ensuring that the end value of one is always less than (or equal to, depending on your problem) the start value of the next.

intervals = [(0.2, 0.3),
             (0.8, 1.0),
             (0.4, 0.6),
             (0.32, 0.38)]

intervals = sorted(intervals)
disjoint = all(intervals[i+1][0] > intervals[i][1] for i in range(len(intervals) - 1))
分享给朋友:
您可能感兴趣的文章:
随机阅读: