评估Python中嵌套整数间隔



这个问题是关于嵌套整数间隔的间隔比较。

假定三个整数范围,为了简单起见,我称之为目标范围。这些目标范围永远不会重叠,但长度可能不同。

> target1 = range(1,10000)
> target2 = range(10001,20000)
> target3 = range(20001,25000)

进一步假设我称之为另一个范围测试范围,其长度总是比任何目标范围都小,但可能会跨入相邻的目标范围。

> test1 = range(900,5000)  # entirely in target1
> test2 = range(9900,10500)  # mostly in target2, but crosses into target1

是否有python函数可以帮助识别哪个目标范围 a 测试范围 属于?如果测试范围越过相邻的目标范围,则只能给出该目标范围的测试范围中最大比例的目标范围。

> sought_function(test1, [target1, target2, target3])
# 1
> sought_function(test2, [target1, target2, target3])
# 2

编辑1

在没有标准的Python函数以进行间隔比较嵌套整数间隔的情况下,您将使用什么代码?以下是一些函数的快速且笨拙的Python代码,标题为 nested_in__in_th 肯定可以改进。

def nested_in_which(test, targets):
    for n, t in enumerate(targets):
        if test[0] in t and test[-1] in t:
            return(n)
        else:
            if test[0] in t and n < len(targets) and test[-1] in targets[n+1]:
                return(n+1) # Overlap comparison not yet implemented

如果您将每个范围视为一组。您需要目标范围,使您与测试集具有最大的交集。

因此,如果您计算每个目标与测试之间的交点的长度并返回最大交叉点的索引,则应拥有您想要的。

这是一些粗略的代码:

def which_range( testRange, *targetRanges ):
    testRange = set( testRange )
    tests = [ ( i, len( set( targetRange ).intersection( testRange ) ) ) for i, targetRange in enumerate( targetRanges ) ]
    return max( tests, key=lambda x: x[1] )[0]

>>> which_range( range(9900,10500), range(1,10000), range(10001,20000), range(20001,25000) )
1 # the second target range
>>> which_range( range(900,5000), range(1,10000), range(10001,20000), range(20001,25000) )
0 # the first target range

不确定您是否想做尝试,但是如果要检查目标范围中的测试范围是否包括:

test1[0] in target1 and test1[-1] in target1
=> True

最新更新