确定多组整数的交集是否为非空的最快方法是什么?

时间:2019-04-15 04:50:30

标签: python math set

我是本科数学组的成员。我有一组独特的整数集合(集合的长度是可变的)。很多时候,我需要确定集合中所有集合的交集是否为非空。我不需要知道交集是什么,只要它是非空的就行。我必须做很多事情。我没有太多的时间复杂度和制定高效算法的经验。最快的方法是什么?

我包括了到目前为止的内容。这太慢了。如果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

2 个答案:

答案 0 :(得分:1)

集合交集可以接受多个集合

#include<iostream>
using namespace std;
#include"DVD.h"
#include"HarryPotterDVD.h"

int main() {
    HarryPotterDVD h1;
    HarryPotterDVD h2(1, "Chamber of Secrets", "Chris Columbus", 2, "Tom Riddle");
    HarryPotterDVD h3(h2);
    h1 = h3;
    cout << h2.getEpisode() << endl;
    cout << h2.getAntagonist() << endl;
    h3.display();
    h1.setEpisode(5);
    h1.setAntagonist("Prabesh");
    h1.display();
}

(甚至只是S[0].intersection(*S[1:])

例如

set.intersection(*S)

答案 1 :(得分:1)

另一种方法是将所有内容放入set.intersection

import numpy as np

S = [set(np.random.randint(0,100,100)) for _ in range(20)]
set.intersection(*S)
# set()