Python中两组间隔之间的补码 [英] complement between two sets of intervals in Python

查看:60
本文介绍了Python中两组间隔之间的补码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两组不相交的间隔,我想找到仅包含在一组中的间隔(这是一组中间隔的对称补码).

I have two sets of disjoint intervals and I want to find the intervals that contained in only one of the sets (this is kind of symmetric complement of the intervals in the sets).

例如1:

set1 = [[0, 2], [4, 10]]
set2 = [[1,2], [4, 10]]

预期的结果是:

sub_intervals_in_one_set_only = [[0,1]]

[[0,1]]仅包含在set1中(在[0,2]中),但不包含在set2中的任何间隔中.

[[0,1]] containd in the only in set1 (in [0,2]) but not contained in any interval in set2.

例如2:

set1 = [[0.1, 0.2], [0.4, 0.6], [0.65, 0.66], [0.8, 1]]
set2 = [[0, 0.21], [0.42, 0.6], [0.8, 1]]

预期的结果是:

sub_intervals_in_one_set_only = [[0,0.1],[0.2,0.21], [0.4,0.42], [0.65, 0.66]]

[0,0.1], [0.2,0.21]仅包含在set2中,[0.4,0.42], [0.65, 0.66]仅包含在set1中.

[0,0.1], [0.2,0.21] included only in set2, [0.4,0.42], [0.65, 0.66] included only in set1.

我试图找到与代码

I trying with finding the intersection with the code here. But didn't succeed from there.

我将很高兴为您提供任何帮助. 谢谢!

I will be glad to any help. Thanks!

推荐答案

您可以使用:

from functools import reduce
from operator import xor
from itertools import chain


set1 = [[0.1, 0.2], [0.4, 0.6], [0.65, 0.66], [0.8, 1]]
set2 = [[0, 0.21], [0.42, 0.6], [0.8, 1]]

l = sorted((reduce(xor, map(set, chain(set1 , set2)))))
[l[i:i + 2] for i in range(0, len(l), 2)]

输出:

[[0, 0.1], [0.2, 0.21], [0.4, 0.42], [0.65, 0.66]]

这篇关于Python中两组间隔之间的补码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆