Hatefiend
Hatefiend

Reputation: 3596

XOR operation on three values

I have three boolean values. I need to return false if all three are true or if all three are false. I will return true in every other situation. Based on my research, in some specifications this is called a three-variable exclusive-or.

Edit: Some specifications claim a three variable XOR involves the only true result would come from a set where only one parameter is true. The XOR I am referring to here is of another specification where multiple values may be true, but not all.

Here's the truth table for my desired operation (xor with three params).

A   B   C   -
T   T   T   F
T   T   F   T
T   F   T   T
T   F   F   T
F   T   T   T
F   T   F   T
F   F   T   T
F   F   F   F

Upvotes: 6

Views: 20041

Answers (4)

Xuan Quyen Nguyen
Xuan Quyen Nguyen

Reputation: 1

If all 3 are true or all 3 are false, I think the best way is:

if (a AND b AND c) or (not a AND not b AND not c):
    # Do something

If you only want it returns true when one and only one of the values is true:

if int(a) + int(b) + int(c) == 1:
    # Do something

Many thanks!

Upvotes: 0

subdeveloper
subdeveloper

Reputation: 2668

Use this :

(A XOR B) OR (B XOR C)

Works for n inputs as well :

(A XOR B) OR (B XOR C) OR ...(n XOR n+1)

Upvotes: 4

abhinit21
abhinit21

Reputation: 341

Hear is my python implementation of it

def xor_three(a, b, c):
    return (a ^ b) or (b ^ c)

A = True
B = False
C = True

print(xor_three(A, B, C))

Upvotes: 1

Leandro Keen Zapa
Leandro Keen Zapa

Reputation: 196

To make an algorithm for that, you need to know how to use karnaugh map in three variable. See sample karnaugh map here

Ok. First, to make things easier replace T as 1 and F as 0 in your truth table.

At first glance, it is just an increasing 3-bit binary. So arranging it in an increasing way is a good idea. Take a look below.

A   B   C       F(A,B,C)
0   0   0       0
0   0   1       1
0   1   0       1
0   1   1       1
1   0   0       1
1   0   1       1
1   1   0       1
1   1   1       0

By using karnaugh-map, you will get a boolean expression below. For the first expression we get A'B .

see image 1

For the second expression AB' .

see image 2

For the third expression B'C .

see image 3

For the fourth expression BC' .

enter image description here

To simply understand karnaugh-map, if all 1's are inside the straight sight towards the table of a variable then one term of expression will contain only that variable. But if 1's are outside the straight sight of that variable, then, it is a compliment of that variable.

F(A,B,C) = A'B + AB'+ B'C + BC'

but since

A XOR B = AB'+ A'B
B XOR C = BC'+ B'C

then our simplified form will be

F(A,B,C) = A XOR B + B XOR C

for pseudo code programming, it is equivalent to

result = (A XOR B) OR (B XOR C)
//other else
result = (A ^ B) | (B ^ C)

Upvotes: 8

Related Questions