比较 python 中交集的开放范围

Compare open ranges in python for intersection

我比较范围如下:

def get_intersections(ranges):
    """Marks ranges if they intersect with other ranges with True.
    """
    intersection_idxs = len(ranges) * [False]
    for idx in range(len(ranges)):
        r, rest = set(ranges[idx]), [set(_) for _ in ranges[:idx] + ranges[idx+1:]]
        # Uncomment to understand.
        # print(r)
        # print(rest)
        if any([len(set.intersection(r, r2)) > 0 for r2 in rest]):
            intersection_idxs[idx] = True
    return intersection_idxs

# Example 1.
ran1 = range(4,9)
ran2 = range(2,5)
ran3 = range(2,3)
ranges = [ran1, ran2, ran3]
print(get_intersections(ranges))

# Example 2.
ran1 = range(1,5)
ran2 = range(2,5)
ran3 = range(7,9)
ranges = [ran1, ran2, ran3]
print(get_intersections(ranges))

# Example 3.
#ran1 = range(1,inf)
#ran2 = range(2,5)
#ran3 = range(7,9)
#ranges = [ran1, ran2, ran3]
#print(get_intersections(ranges))
#>> [True, True, True]

如您所见,前两个示例运行良好。由于第一个示例中所有范围相交,get_intersections 函数 returns [True, True, True].

在第二个示例中,最后一个范围 (range(7,9)) 不与其他范围相交。因此返回 [True, True, False]。

我想实现示例 3(参见伪代码)。在这种情况下,第一个范围从 1 到无穷大,这意味着它与其他范围相交。因此,其他范围也会自动相交。现在我不知道该怎么做。有没有办法以类似的方式使用开放范围或范围到无穷大?

我不知道你为什么要用range

您可以使用具有下限和上限 (a,b) 的元组。

当你需要inf时,你可以使用math.inf,它比任何实数都大。

所以 (a,b)(c,d) 相交 if c<b and a<d.

你没看错,Frane。这是一个设计缺陷。这是我的代码:

def get_intersections(lis):
    """Marks ranges if they intersect with other ranges with True.
    """
    intersection_idxs = len(ranges) * [False]
    for idx in range(len(lis)):
        r, rest = lis[idx], ranges[:idx] + ranges[idx+1:]
        # Uncomment to understand.
        # print(r)
        # print(rest)
        if any([r2[0] <= r[1] and r[0] <= r2[1] for r2 in rest]):
            intersection_idxs[idx] = True
    return intersection_idxs

# Example 1.
ranges = [(4,9), (2,5), (2,3)]
assert(get_intersections(ranges) == 3 * [True])
# Example 2.
ranges = [(1,5), (2,5), (7,9)]
assert(get_intersections(ranges) == [True, True, False])
# Example 3.
ranges = [(1,float('inf')), (2,5), (7,9)]
assert(get_intersections(ranges) == [True, True, True])
# Example 4.
ranges = [(1,2), (4,float('inf')), (7,9)]
assert(get_intersections(ranges) == [False, True, True])