Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity of python "set.intersection" for n sets

Tags:

python

I want to know the complexity of the set.intersection of python. I looked in the documentations and the online wikis for python, but I did not find the time complexity of this method for multiple sets.

like image 751
M.M Avatar asked Jun 15 '15 12:06

M.M


People also ask

What is the time complexity of set intersection Python?

The python wiki on time complexity lists a single intersection as O(min(len(s), len(t)) where s and t are the sizes of the sets and t is a set.

What is the time complexity of set function in Python?

Creating Set:- In Python, Sets are created through set() function. An Empty list is created. Note that empty Set cannot be created through {}, it creates dictionary. Checking if an item is in : Time complexity of this operation is O(1) on average.

How do you find the intersection of multiple sets in Python?

To intersect multiple sets, stored in a list l , use the Python one-liner l. pop(). intersection(*l) that takes the first set from the list, calls the intersection() method on it, and passes the remaining sets as arguments by unpacking them from the list.

How does Python set intersection work?

Intersection() function Python The intersection of two given sets is the largest set, which contains all the elements that are common to both sets. The intersection of two given sets A and B is a set which consists of all the elements which are common to both A and B.


Video Answer


1 Answers

The python wiki on time complexity lists a single intersection as O(min(len(s), len(t)) where s and t are the sizes of the sets and t is a set. (In English: the time is bounded by and linear in the size of the smaller set.)

Note: based on the comments below, this wiki entry had been be wrong if the argument passed is not a set. I've corrected the wiki entry.

If you have n sets (sets, not iterables), you'll do n-1 intersections and the time can be (n-1)O(len(s)) where s is the set with the smallest size.

Note that as you do an intersection the result may get smaller, so although O is the worst case, in practice, the time will be better than this.

However, looking at the specific code this idea of taking the min() only applies to a single pair of sets and doesn't extend to multiple sets. So in this case, we have to be pessimistic and take s as the set with the largest size.

like image 87
rocky Avatar answered Sep 28 '22 12:09

rocky