Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if only one variable in a list of variables is set

Tags:

python

xor

I'm looking for a simple method to check if only one variable in a list of variables has a True value. I've looked at this logical xor post and is trying to find a way to adapt to multiple variables and only one true.

Example

>>>TrueXor(1,0,0)
True

>>>TrueXor(0,0,1)
True

>>>TrueXor(1,1,0)
False

>>>TrueXor(0,0,0,0,0)
False
like image 734
Deon Avatar asked Jun 23 '09 12:06

Deon


People also ask

How do you check if a variable has a specific value in Python?

To check if a local variable exists in Python, use the in operator against the output of locals() function, which has a dictionary of a current local variables table. The “in operator” returns a boolean value. If a variable exists, it returns True otherwise False.

How do you check if an element is in a list more than once?

Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count().

How do you check if multiple values are none in Python?

To check if multiple variables are not None: Wrap the variables in a sequence (e.g. a tuple or a list). Use the not in operator to check if None is not a member of the sequence. If the sequence doesn't contain None , then the variables are not None .

How do you check if two variables are true?

The equality operator ( == ) compares two variables for equality and returns True if they are equal. Otherwise, it returns False . Since a and b references the same object, they're both identical and equal.


1 Answers

There isn't one built in but it's not to hard to roll you own:

def TrueXor(*args):
    return sum(args) == 1

Since "[b]ooleans are a subtype of plain integers" (source) you can sum the list of integers quite easily and you can also pass true booleans into this function as well.

So these two calls are homogeneous:

TrueXor(1, 0, 0)
TrueXor(True, False, False)

If you want explicit boolean conversion: sum( bool(x) for x in args ) == 1.

like image 57
Andrew Hare Avatar answered Oct 20 '22 00:10

Andrew Hare