我是本科生数学小组的成员。我有一组唯一整数的集合(集合的长度不同)。我经常需要确定集合中所有集合的交集是否非空。我不需要知道交集是什么,只需要知道它是否非空。我必须经常这样做。我在时间复杂度和制定高效算法方面没有太多经验。最快的方法是什么?
我已经包含了迄今为止所拥有的内容。速度慢得可怕。如果 S 有 15 组以上,那么脚本将永远持续下去。
# S is an array of integers
def intersects(S):
if S == []:
return True # if S is empty, I deem the intersection nonempty for reasons
A = S[0]
for i in range(1, len(S)):
B = S[i]
A = get_intersection(A, B) # returns intersection of A and B
if A == []:
return False
return True
最佳答案
集合交集可以接受多个集合
S[0].intersection(*S[1:])
(甚至只是set.intersection(*S)
)
例如
>>> s1 = set([1,2,3])
>>> s2 = 2,3,4
>>> s3 = 3,4,5
>>> s1.intersection(s2,s3)
set([3])
关于python - 确定多组整数的交集是否非空的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55682754/