2
WalkingBed
340d

# Is there a way to simplify the following boolean expression..?? (x && !y) || (!x && y)

• 14
Xor
• 1
And she is correct

>>> def foo(x, y):
>>> print((x and (not y)) or ((not x) and y))
>>>
>>> def bar(x, y):
>>> print(x != y)
>>>
>>> def printer(func):
>>> func(False,False)
>>> func(False,True)
>>> func(True,False)
>>> func(True,True)

>>> printer(foo)
>>> print("--------")
>>> printer(bar)

False
True
True
False
--------
False
True
True
False
• 2
Yes, thanks @Voxera.

I forgot to mention javascript tag, but I was able to find a simplified ternary operator version for this through her comment.

(x ? !y : y)
• 3
@shehanthamel (!x ^ !y), or (!x != !y) (if x and y are already both booleans, you can just write x^y or x!=y)
• 2
DeMorgan Laws.

Learn them.
• 1
@shehanthamel That works, but I'd probably use the first just for the sake of writing clear code.

If they're bools, perhaps x !== y?
• 1
@shehanthamel
If its Javascript then you can do one of:
x ^ y - runs xor for x and y, works well in this case if x and y are bool only. Returns 1 or 0.
!!x ^ !!y - converts to bool and runs xor. Returns 1 or 0.
!!(!!x ^ !!y) - converts to bool, runs xor, converts result to bool true / false.

So pick one for your use case :)