Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the algorithm of 'set.intersection()' in python?

First of all, my purpose is to randomly get only one element in both known sets. So my original method is firstly intersect two sets. And then randomly pick up a element from the intersected set. But this is foolish, because that I only need a elements but a intersected set.

So I need to find the algorithm of set.intersection().

I compare the cost time between the methods of 'set.intersection()' and 'for{for{}}'. Set.intersection() is more faster than other one(100 times). So using 'for{for{}}' to pick up a randomly elements is not a wise idea.

What's the algorithm behind set.intersection() in python?

like image 742
Ding Ding Avatar asked Nov 20 '13 15:11

Ding Ding


People also ask

How does Python set intersection work?

Python Set intersection() MethodThe intersection() method returns a set that contains the similarity between two or more sets. Meaning: The returned set contains only items that exist in both sets, or in all sets if the comparison is done with more than two sets.

How do you calculate intersection in Python?

We can use a method called intersection in python and set intersection operator, i.e. &, to get the intersection of two or more sets. The set intersection operator only works with sets, but the set intersection() method can be used with any iterable, like strings, lists, and dictionaries.

Which operator is used to intersect two sets Python?

The intersection of two sets is the set of all the common elements of both the sets. You can use the intersection() method of the & operator to find the intersection of a Python set.

What is the time complexity of Python set intersection?

What is the Time Complexity of Set Intersection in Python? The runtime complexity of the set. intersection() method on a set with n elements and a set argument with m elements is O(min(n, m)) because you need to check for the smaller set whether each of its elements is a member of the larger set.


1 Answers

The algorithm is as follows: the smaller set is looped over and every element is copied depending whether it's found in the bigger set. So, it's the C equivalent of

def intersect(a, b):
    if len(a) > len(b):
        a, b = b, a

    c = set()
    for x in a:
        if x in b:
            c.add(x)
    return c

(Or: return set(x for x in a if x in b).)

like image 50
Fred Foo Avatar answered Oct 12 '22 22:10

Fred Foo