Bob Dunakey Bob Dunakey - 7 months ago 35
Python Question

Writing a Boolean Expression using Python

I am trying to write a boolean expression in Python, but it appears Python can only do XOR expressions with bit operations.

What would be the best way to go about writing this expression in Python without the XOR operator.

(A ^ B ^ C ^ D) U ((B U C U D)' XOR A)


I've attempted this:

if (A and B and C and D) or ((A and not (B or C or D)) or (not A and (B and C and D))):

and I'm looking to simplify it.


Just use the bitwise ^ operator. Python's booleans return a boolean when ^-ed together:

>>> True ^ True
>>> True ^ False

The and and or operators exist primarily to support short-circuiting, but XOR can't short-circuit.

There's also !=:

>>> True != True
>>> True != False

but that doesn't do what you want when chained with more arguments:

>>> True != True != True