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?
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.
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.
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 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.
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)
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With