Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning boolean if set is empty

I am struggling to find a more clean way of returning a boolean value if my set is empty at the end of my function

I take the intersection of two sets, and want to return True or False based on if the resulting set is empty.

def myfunc(a,b):     c = a.intersection(b)     #...return boolean here 

My initial thought was to do

return c is not None 

However, in my interpreter I can easily see that statement will return true if c = set([])

>>> c = set([]) >>> c is not None True 

I've also tried all of the following:

>>> c == None False >>> c == False False >>> c is None False 

Now I've read from the documentation that I can only use and, or, and not with empty sets to deduce a boolean value. So far, the only thing I can come up with is returning not not c

>>> not not c False >>> not c True 

I have a feeling there is a much more pythonic way to do this, by I am struggling to find it. I don't want to return the actual set to an if statement because I don't need the values, I just want to know if they intersect.

like image 212
C.B. Avatar asked Jan 17 '14 16:01

C.B.


People also ask

How do you check if a set is empty?

Set. isEmpty() method is used to check if a Set is empty or not. It returns True if the Set is empty otherwise it returns False.

Is an empty set false Python?

In python, an empty set always evaluates to false. So when we passed an empty set to the if condition it'll be evaluated to false. But the not operator reverses the false value to true value. Thus the if condition is set to true.

How do you represent an empty set in Python?

Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements, we use the set() function without any argument.

How do I print an empty set?

To create an empty set in python we have to use the set() function without any arguments, if we will use empty curly braces ” {} ” then we will get an empty dictionary. After writing the above code (create an empty set in python), Ones you will print “type(x)” then the output will appear as a “ <class 'set'> ”.


2 Answers

not as pythonic as the other answers, but mathematics:

return len(c) == 0 

As some comments wondered about the impact len(set) could have on complexity. It is O(1) as shown in the source code given it relies on a variable that tracks the usage of the set.

static Py_ssize_t set_len(PyObject *so) {     return ((PySetObject *)so)->used; } 
like image 131
gefei Avatar answered Oct 12 '22 10:10

gefei


def myfunc(a,b):     c = a.intersection(b)     return bool(c) 

bool() will do something similar to not not, but more ideomatic and clear.

like image 38
Jonas Schäfer Avatar answered Oct 12 '22 11:10

Jonas Schäfer