简体   繁体   English

检查两个集合在Python中是否相等的时间复杂性

[英]Time-complexity of checking if two set are equal in Python

Reading this question , I wondered how much time (asymptotically speaking) does it takes to Python to evaluate expressions like 阅读此问题 ,我想知道使用Python评估像这样的表达式需要多少时间(渐近而言)

{1,2}=={2,1}

that is to say, to check if two instances of the set class are equal. 也就是说,检查set类的两个实例是否相等。

Comparison between sets is implemented by the function set_richcompare in setobject.c , line 1848 . 集之间的比较由set_richcompare中第1848行的setobject.c函数实现。 You'll see that equality is implemented as follows: 您将看到平等实现如下:

  1. If the sets do not have the same size, return false. 如果集合的大小不同,则返回false。

  2. If both sets have been hashed, and the hashes differ, return false. 如果两个集合都已被哈希处理,并且哈希值不同,则返回false。

  3. Call set_issubset . 调用set_issubset

The subset test for two sets looks like this: 两组的子集测试如下所示:

while (set_next(so, &pos, &entry)) {
    int rv = set_contains_entry((PySetObject *)other, entry);
    if (rv == -1)
        return NULL;
    if (!rv)
        Py_RETURN_FALSE;
}
Py_RETURN_TRUE;

You'll see that it works by iterating over all the elements of the first set and then looking up each one in the other set. 您将通过遍历第一组的所有元素然后在另一组中查找每个元素来看到它的工作原理。 So (unless there are a lot of hash collisions) this is linear in the size of the first set. 因此(除非有很多哈希冲突),这在第一组中是线性的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM