xor operator?

Alex Martelli aleaxit at yahoo.com
Fri Jan 26 11:04:13 EST 2001


"Hans Nowak" <ivnowa at hvision.nl> wrote in message
news:3A71951D.20A2 at hvision.nl...
    [snip]
> > In the specific Python
> > > sense, the return value of the boolean xor operation would also be
vague.
>
> Simply 0 or 1 would be a possibility, but that is not what Python's
> 'and' and 'or' do. So maybe, if it evaluates to true, it returns the
> 'true' element; otherwise it returns 0 (like 'and' and 'or' do).

My approach was somewhat different:

def xor(a, b):
    if not a: return b
    if not b: return a

This returns one of the two arguments *if possible at all* -- if
only one is true, that one; if both are false, one of them (in
this coding, as it happens, the second one -- though here I'd
really like a non-deterministic Djikstra guarded-statement more
than a deterministic/sequential approach, but, oh well:-).

Only when both arguments are true is it impossible to return
either argument, and then I prefer to return None -- inter alia,
because that is what happens automatically.

Note that it's *NOT* true that Python's 'and' and 'or' "return 0";
they ALWAYS return the value of one of the arguments you have
passed!!!  'and' returns the first if false, else the second;
'or' returns the first if true, else the second.

Check this...:

for a, b in [(x,y) for x in ['','x'] for y in [[],[7]]]:
    print "%6r & %6r -> %6r" % (
        a, b, a and b)
print
for a, b in [(x,y) for x in ['','x'] for y in [[],[7]]]:
    print "%6r | %6r -> %6r" % (
        a, b, a or b)
print
for a, b in [(x,y) for x in ['','x'] for y in [[],[7]]]:
    print "%6r ^ %6r -> %6r" % (
        a, b, xor(a,b))
print

This will emit:

    '' &     [] ->     ''
    '' &    [7] ->     ''
   'x' &     [] ->     []
   'x' &    [7] ->    [7]

    '' |     [] ->     []
    '' |    [7] ->    [7]
   'x' |     [] ->    'x'
   'x' |    [7] ->    'x'

    '' ^     [] ->     []
    '' ^    [7] ->    [7]
   'x' ^     [] ->    'x'
   'x' ^    [7] ->   None

as you can see -- no 0 in sight; the output value will
ALWAYS be one of the two input ones -- except for the
very last case of xor, where a 'None' (or other false
value, but None seems most Pythonic) must be inserted.


Alex







More information about the Python-list mailing list