Re: missing 'xor' Boolean operator

2009-07-27 Thread Terry Reedy

greg wrote:

Terry Reedy wrote:


In Math and Python, abc means ab and bc, not (ab)c or a(bc).
!= is a comparison operator like ,


Although Python extends the chaining principle to
!=, this is somewhat questionable, because
a  b and b  c implies a  c, but a != b and
b != c does not imply a != c.

I'm not sure I've ever seen a mathematician
write a != b != c, but if I did, I would tend
to think he meant to say that none of a, b,
c are equal to any other. That's not what it
means in Python, though.


However, == is transitive, and a == b == c is quite common.
It would hardly do to have different rules for !=.

Either we have a uniform rule for a compare_op b compare_ob c, as we do, 
or we have several fussy rules that would be hard to remember.


--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-27 Thread Mark Dickinson
On Jul 27, 1:53 am, Delaney, Timothy (Tim) tdela...@avaya.com
wrote:
 Mark Dickinson wrote:
  Since the 'and' and 'or' already return objects (and objects
  evaluate to true or false), then 'xor' should behave likewise, IMO.
  I expect that would be the case if it were ever added to the
  language.

  I'm not so sure.  Did you ever wonder why the any() and all()
  functions introduced in 2.5 return a boolean rather than returning
  one of their arguments?  (I did, and I'm still not sure what the
  answer is.)

 Consider the case of any() and all() operating on an empty iterable.
 What type should they return?

 It is impossible in the case of any() and all() to always return one of
 the elements due to this edge case.

Yes, of course; the alternative implementation I was thinking of
was the one that I implemented eons ago for my own pre-2.5 code,
where I defined any and all roughly as:

any([x1, x2, x3, ...]) - False or x1 or x2 or x3 or ...
all([x1, x2, x3, ...]) - True and x1 and x2 and x3 and ...

At the time this seemed like the obvious choice, so I was a bit
surprised when it was chosen to always return a bool instead in
the official versions.

Now that I'm older and wise^H^H^H^H, well, maybe just older, the
pure bool version seems cleaner and less error-prone, even if
it's mildly inconsistent with the behaviour of and and or.

Mark
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: missing 'xor' Boolean operator

2009-07-26 Thread Delaney, Timothy (Tim)
Mark Dickinson wrote:

 Since the 'and' and 'or' already return objects (and objects
 evaluate to true or false), then 'xor' should behave likewise, IMO.
 I expect that would be the case if it were ever added to the
 language. 
 
 I'm not so sure.  Did you ever wonder why the any() and all()
 functions introduced in 2.5 return a boolean rather than returning
 one of their arguments?  (I did, and I'm still not sure what the
 answer is.)

Consider the case of any() and all() operating on an empty iterable.
What type should they return?

It is impossible in the case of any() and all() to always return one of
the elements due to this edge case. Similarly, it is impossible in all
cases for a boolean xor to return one of the arguments - if both
arguments evaluate to a true (Something) value, xor must return a false
(Nothing) result.

Tim Delaney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-26 Thread greg

Terry Reedy wrote:


In Math and Python, abc means ab and bc, not (ab)c or a(bc).
!= is a comparison operator like ,


Although Python extends the chaining principle to
!=, this is somewhat questionable, because
a  b and b  c implies a  c, but a != b and
b != c does not imply a != c.

I'm not sure I've ever seen a mathematician
write a != b != c, but if I did, I would tend
to think he meant to say that none of a, b,
c are equal to any other. That's not what it
means in Python, though.

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-25 Thread Albert van der Horst
In article mailman.3164.1247670958.8015.python-l...@python.org,
Jean-Michel Pichavant  jeanmic...@sequans.com wrote:
Christian Heimes wrote:
 Chris Rebert wrote:

 Using the xor bitwise operator is also an option:
 bool(x) ^ bool(y)


 I prefer something like:

 bool(a) + bool(b) == 1

 It works even for multiple tests (super xor):

   if bool(a) + bool(b) + bool(c) + bool(d) != 1:
   raise ValueError(Exactly one of a, b, c and d must be true)

 Christian


While everyone's trying to tell the OP how to workaround the missing xor
operator, nobody answered the question why is there no xor operator ?.

If the question was Why is there no 'or' operator ?, would because A
or B = not(not A and not B) be a proper answer ?

No. I think it is because and/or can be extended to be sensible
in a context where objects can be used. (What others have expressed
as having short-circuit evaluation. So sce indeed is the underlying
reason that and/or can be extended sensibly to objects.)

Remains whether we need an xor that only works and requires that
both operands are booleans. That one we have already!
It is called != .

(a!=b)!=c
and
a!=(b!=c)

are the same for booleans, so can indeed be expressed
a!=b!=c   (associativy of xor)


JM

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
alb...@spearc.xs4all.nl =n http://home.hccnet.nl/a.w.m.van.der.horst

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-25 Thread Terry Reedy

Albert van der Horst wrote:


Remains whether we need an xor that only works and requires that
both operands are booleans. That one we have already!
It is called != .

(a!=b)!=c
and
a!=(b!=c)

are the same for booleans, so can indeed be expressed
a!=b!=c   (associativy of xor)


Not in Python

 a,b,c = True, False, True
 (a!=b)!=c
False
 a!=(b!=c)
False
 a!=b!=c
True
 (a!=b) and (b!=c)
True

In Math and Python, abc means ab and bc, not (ab)c or a(bc).
!= is a comparison operator like , not an arithmetic operator like + 
(or logical xor). If one has 0/1 or True/False values, we have 
arithmetic xor already, ^, which works as expected.


 (a^b)^c
False
 a^b^c
False

Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-21 Thread Mark Dickinson
On Jul 20, 11:34 pm, Ethan Furman et...@stoneleaf.us wrote:
 Dr. Phillip M. Feldman wrote:
   Suppose that 'xor' returns the value that is true when only one value is
   true, and False otherwise.  This definition of xor doesn't have the
 standard
   associative property, that is,
  
   (a xor b) xor c
  
   will not necessarily equal
  
   a xor (b xor c)
  
   To see that this is the case, let a= 1, b= 2, and c= 3.
  
   (a xor b) xor c
  
   yields 3, while
  
   a xor (b xor c)
  
   yields 1.  So, I'd prefer an xor operator that simply returns True or
 False.
  
   Phillip
  

 You are, of course, free to write your version however it makes sense to
 you and your team.  :)

 Since the 'and' and 'or' already return objects (and objects evaluate to
 true or false), then 'xor' should behave likewise, IMO.  I expect that
 would be the case if it were ever added to the language.

I'm not so sure.  Did you ever wonder why the any() and all()
functions introduced in 2.5 return a boolean rather than returning
one of their arguments?  (I did, and I'm still not sure what the
answer is.)

Mark
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-21 Thread Ethan Furman

Mark Dickinson wrote:

On Jul 20, 11:34 pm, Ethan Furman et...@stoneleaf.us wrote:


Dr. Phillip M. Feldman wrote:
 Suppose that 'xor' returns the value that is true when only one value is
 true, and False otherwise.  This definition of xor doesn't have the
standard
 associative property, that is,

 (a xor b) xor c

 will not necessarily equal

 a xor (b xor c)

 To see that this is the case, let a= 1, b= 2, and c= 3.

 (a xor b) xor c

 yields 3, while

 a xor (b xor c)

 yields 1.  So, I'd prefer an xor operator that simply returns True or
False.

 Phillip


You are, of course, free to write your version however it makes sense to
you and your team.  :)

Since the 'and' and 'or' already return objects (and objects evaluate to
true or false), then 'xor' should behave likewise, IMO.  I expect that
would be the case if it were ever added to the language.



I'm not so sure.  Did you ever wonder why the any() and all()
functions introduced in 2.5 return a boolean rather than returning
one of their arguments?  (I did, and I'm still not sure what the
answer is.)

Mark



Very good question -- I likewise do not know the answer.  I will only 
observe that any() and all() are functions, while 'and' and 'or' are 
not.  If one wanted the object-returning behavior one could string 
together 'or's or 'and's instead.


~Ethan~
--
Thinking out loud here -- YMMV.  :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-20 Thread Ethan Furman

[fixed for bottom-posting]

Dr. Phillip M. Feldman wrote:

MRAB-2 wrote:



snip

What values should 'xor' return? IMHO, if only one of the values is true
then it should return that value, otherwise it should return False.

1 xor 0 = 1
0 xor 2 = 2
1 xor 2 = False
0 xor 0 = False

This is because it's a Boolean operator, so it should fall back to
Boolean values when necessary, like 'not':

not 0 = True
not 1 = False

Also:

x and y and z = (x and y) and z
x or y or z = (x or y) or z

therefore:

x xor y xor z = (x xor y) xor z


 Suppose that 'xor' returns the value that is true when only one value is
 true, and False otherwise.  This definition of xor doesn't have the 
standard

 associative property, that is,

 (a xor b) xor c

 will not necessarily equal

 a xor (b xor c)

 To see that this is the case, let a= 1, b= 2, and c= 3.

 (a xor b) xor c

 yields 3, while

 a xor (b xor c)

 yields 1.  So, I'd prefer an xor operator that simply returns True or 
False.


 Phillip


You are, of course, free to write your version however it makes sense to 
you and your team.  :)


Since the 'and' and 'or' already return objects (and objects evaluate to 
true or false), then 'xor' should behave likewise, IMO.  I expect that 
would be the case if it were ever added to the language.


~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-18 Thread Mark Dickinson
On Jul 17, 12:06 pm, Jean-Michel Pichavant jeanmic...@sequans.com
wrote:
 I was saying that using boolean operators with object instead of boolean
 values is error prone,

I agree with this to some extent.  After all, Python conditional
expressions were eventually introduced in response to buggy uses of
the 'a and b or c' idiom.  See PEP 308, and:

http://mail.python.org/pipermail/python-dev/2005-September/056546.html

In my own code, I'm finding myself increasingly using conditional
expressions where I would once have used 'and' or 'or':

daysInAdvance = int(inputVar) if inputVar is not None else 0

--
Mark
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-17 Thread Jean-Michel Pichavant

Luis Alberto Zarrabeitia Gomez wrote:

Quoting Jean-Michel Pichavant jeanmic...@sequans.com:

  

Emile van Sebille wrote:


On 7/16/2009 7:04 AM Unknown said...
  

On 2009-07-16, Emile van Sebille em...@fenx.com wrote:


daysInAdvance = int(inputVar) or 25
  

I don't get it.  That doesn't work right when inputVar == 0.


Aah, but you didn't get to define right.  :)  For that particular 
example 0 is not a valid response.
  
When I was talking about such error prone form of boolean operations, I 
didn't expect to be right so quickly :p



What do you mean by being right so quickly, and error prone in this context?
I would also ask Unknown why he believes that int(intputVar) or 25 doesn't
work right when inputVar == 0. The only false value that int() may return is
zero, so the or 25 clause is there only for that case. I can't see then how
you think that is an error.
  


I was saying that using boolean operators with object instead of boolean 
values is error prone, cause no language behaves he same way, and all 
behaviors are conventions difficult to figure out without diving deeply 
into the documentation (or being explained as it happened to me).


I think the initialization trick is an error, because I don't want 
foo(0) to set daysInAdvance to 25. I'll want it to set the attribute to 
0, cause 0 is a valid integer. 0 is a valid integer content, None 
wouldn't be a valid integer content.



JM
--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-17 Thread Steven D'Aprano
On Thu, 16 Jul 2009 15:53:45 +0200, Jean-Michel Pichavant wrote:

 Python has extended the algebra definition of or and and top any
 type, but it is so unintuitive (I'm no LISP programmer).

I disagree. The Something/Nothing dichotomy is so intuitive to me that I 
would hate to go back to a language that only accepted booleans as 
arguments to `if`.


 I think than 
 using the short-circuiting mechanism of bool operators along with the 
 python tricks is just error prone and may result in bug difficult to 
 spot, unless you are very aware of all python boolean mechanisms.

In other words, if you don't know how Python behaves, you will make 
mistakes.

Of course you will. That applies to *anything* -- if you don't know how 
it works, you will make mistakes.

Given three result codes, where 0 means no error and an arbitrary non-
zero integer means some error, it is simple and easy to write:

failed = result_1 or result_2 or result_3

The equivalent:

failed = (result_1 != 0) or (result_2 != 0) or (result_3 != 0)
# or if you prefer:
succeeded = (result_1 == 0) and (result_2 == 0) and (result_3 == 0)

are longer and more difficult to read and easier to get wrong. Even worse 
are tricks like this:

failed = (result_1 + result_2 + result_3) != 0

This obscures the fact that the result codes are flags and makes it seem 
like (flag + flag) is meaningful.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-17 Thread Luis Zarrabeitia
On Friday 17 July 2009 07:06:26 am Jean-Michel Pichavant wrote:

 I was saying that using boolean operators with object instead of boolean
 values is error prone, cause no language behaves he same way,

I don't know of many languages that actively promote the duck typing concept, 
are as highly dynamic as python, have the metaclass concept, treats almost 
all language concepts as first class citizens (including functions and 
classes), and so on. And don't get me started on assignment (which I consider 
very natural, by the way, but apparently most of the popular languages have 
pretty unnatural assignments).

It is error prone if you are expecting the result to be a bool instead of just
behaving like one (it is certainly unexpected, but you shouldn't be expecting 
to get an instance of certain class anyway, for most of python's operations). 
And it is confusing if you are reading the int(inputVar) or 25 line and 
have no idea of what it means (but once you know it, it becomes very 
readable, almost plain english).

 and all 
 behaviors are conventions difficult to figure out without diving deeply
 into the documentation (or being explained as it happened to me).

That happens with many new concepts. Welcome to python, I guess... if you are 
willing to shake some of your expectations from previous programming 
languages, you will enjoy it. My [little] experience teaching python tells me 
that duck typing, non-enforced encapsulation and everything is an 
object are the hardest to accept for the C# folk at my faculty, but once 
past it, they (the few of them who don't leave the course after that) really 
enjoy the language.

 I think the initialization trick is an error, because I don't want
 foo(0) to set daysInAdvance to 25. I'll want it to set the attribute to
 0, cause 0 is a valid integer. 0 is a valid integer content, None
 wouldn't be a valid integer content.

Well, that wouldn't be a problem with or, but with the programmer.

The exact same behaviour could be obtained with

if int(inputValue) == 0:
inputValue = 25

and no or involved.

However, using only

inputValue = inputValue or 25

could have been an error if you only wanted 25 in case inputValue is None.

(the or trick implies certain trust in that the object you have in hand has 
a reasonable definition of truth value).

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-17 Thread Jean-Michel Pichavant

Steven D'Aprano wrote:

On Thu, 16 Jul 2009 15:53:45 +0200, Jean-Michel Pichavant wrote:


Given three result codes, where 0 means no error and an arbitrary non-
zero integer means some error, it is simple and easy to write:

failed = result_1 or result_2 or result_3

The equivalent:

failed = (result_1 != 0) or (result_2 != 0) or (result_3 != 0)
# or if you prefer:
succeeded = (result_1 == 0) and (result_2 == 0) and (result_3 == 0)

  

[snip]

This is, I guess, where we disagree. I find the second proposal less 
error prone, and universally understandable unlike the first one. It may 
be verbose, it may look even lame to some people, but in the end this is 
perfectly reliable, because you manipulate only False or True within the 
boolean operations.


The first form does not clearly show what is the failed criteria. It 
just happens by coincidence that in this case the failed criteria 
matches the Nothingness of result_1, result_2, result_3. What if results 
may be 'OK' or 'KO'.


failed = result_1 or result_2 or result_3
won't work.

failed = (result_1 =='KO') or (result_2 =='KO') or (result_3 =='KO') is 
lame but reliable.



JM
--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-17 Thread Ethan Furman

Jean-Michel Pichavant wrote:

Steven D'Aprano wrote:


On Thu, 16 Jul 2009 15:53:45 +0200, Jean-Michel Pichavant wrote:


Given three result codes, where 0 means no error and an arbitrary non-
zero integer means some error, it is simple and easy to write:

failed = result_1 or result_2 or result_3

The equivalent:

failed = (result_1 != 0) or (result_2 != 0) or (result_3 != 0)
# or if you prefer:
succeeded = (result_1 == 0) and (result_2 == 0) and (result_3 == 0)

  


[snip]

This is, I guess, where we disagree. I find the second proposal less 
error prone, and universally understandable unlike the first one. 


Careful!  The very few (if any) things in this world that can be 
considered universally understandable do *not* include any programming 
language!  :)


It may 
be verbose, it may look even lame to some people, but in the end this is 
perfectly reliable, because you manipulate only False or True within the 
boolean operations.


The first form does not clearly show what is the failed criteria. It 
just happens by coincidence that in this case the failed criteria 
matches the Nothingness of result_1, result_2, result_3. What if results 
may be 'OK' or 'KO'.


As the programmer, particularly a Python programmer, you should be 
taking advantage of Python's strengths, of which this is one.  If, as 
you say, some function uses a something value to indicate an 
undesirable result, then you have to use something akin to your last 
statement.



~Ethan~



failed = result_1 or result_2 or result_3
won't work.

failed = (result_1 =='KO') or (result_2 =='KO') or (result_3 =='KO') is 
lame but reliable.



JM


--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-17 Thread Steven D'Aprano
On Fri, 17 Jul 2009 16:34:57 +0200, Jean-Michel Pichavant wrote:

 Steven D'Aprano wrote:
 On Thu, 16 Jul 2009 15:53:45 +0200, Jean-Michel Pichavant wrote:


 Given three result codes, where 0 means no error and an arbitrary
 non- zero integer means some error, it is simple and easy to write:

 failed = result_1 or result_2 or result_3

 The equivalent:

 failed = (result_1 != 0) or (result_2 != 0) or (result_3 != 0) # or if
 you prefer:
 succeeded = (result_1 == 0) and (result_2 == 0) and (result_3 == 0)


 [snip]
 
 This is, I guess, where we disagree. I find the second proposal less
 error prone, and universally understandable unlike the first one. It may
 be verbose, it may look even lame to some people, but in the end this is
 perfectly reliable, because you manipulate only False or True within the
 boolean operations.

Because it is verbose, it is more error-prone. The more code you have to 
write, the more opportunities you have to make mistakes.

(This holds up to a point, beyond which being more and more terse also 
leads to more errors.)

Boolean algebra is notorious for programmer errors. The more complicated 
the boolean expression, the more often programmers get it wrong. The more 
book-keeping they have to do, the easier it is to get it wrong. All those 
(result != 0) comparisons are mere book-keeping, they don't add anything 
to the code except to force the flag to be True or False.



 The first form does not clearly show what is the failed criteria.

Of course it does: at least one of the three result codes is non-zero. As 
a bonus, failed will be assigned the first non-zero result code (if any).

Your preferred form, on the other hand, folds all the possible error 
codes into True, throwing away useful information:

 result_1 = 0  # success
 result_2 = 0
 result_3 = 15  # failure
 failure = result_1 or result_2 or result_3
 failure
15
 failure = (result_1 != 0) or (result_2 != 0) or (result_3 != 0)
 failure
True



 It
 just happens by coincidence that in this case the failed criteria
 matches the Nothingness of result_1, result_2, result_3. What if results
 may be 'OK' or 'KO'.

Obviously the test you write depends on the data you have to work with. 
Do you think that's surprising?


 failed = result_1 or result_2 or result_3 won't work.

Not in the example you gave, no. Although if I had to work with lots and 
lots of strings of the form 'OK' and 'KO', I'd consider sub-classing 
string:

 class OKString(str):
... def __nonzero__(self):
... if self == 'OK': return True
... elif self == 'KO': return False
... else:
... raise ValueError('invalid result code')
...

 a = OKString('OK')
 b = OKString('KO')
 c = OKString('KO')
 if a and b and c:
... print Success!
... else:  print Failed!
...
Failed!


(I wouldn't bother if I only needed one or two such tests, but if I had 
lots of them, I'd consider it.)

 
 failed = (result_1 =='KO') or (result_2 =='KO') or (result_3 =='KO') is
 lame but reliable.


Yes, it's reliably complicated, reliably easy to get wrong, reliably 
harder to read, and it reliably throws away information.

But apart from those disadvantages, it does the job you want it to do.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-17 Thread Emile van Sebille

On 7/17/2009 7:34 AM Jean-Michel Pichavant said...

Steven D'Aprano wrote:

On Thu, 16 Jul 2009 15:53:45 +0200, Jean-Michel Pichavant wrote:


Given three result codes, where 0 means no error and an arbitrary non-
zero integer means some error, it is simple and easy to write:

failed = result_1 or result_2 or result_3

The equivalent:

failed = (result_1 != 0) or (result_2 != 0) or (result_3 != 0)
# or if you prefer:
succeeded = (result_1 == 0) and (result_2 == 0) and (result_3 == 0)

  

[snip]

This is, I guess, where we disagree. I find the second proposal less 
error prone, and universally understandable unlike the first one. It may 
be verbose, it may look even lame to some people, but in the end this is 
perfectly reliable, because you manipulate only False or True within the 
boolean operations.


The first form does not clearly show what is the failed criteria. It 
just happens by coincidence 


No -- it happens by design because the premise is 'where 0 means no 
error and an arbitrary non-zero integer means some error'.


that in this case the failed criteria 
matches the Nothingness of result_1, result_2, result_3. What if results 
may be 'OK' or 'KO'.


Which by definition won't happen for the example cited...



failed = result_1 or result_2 or result_3
won't work.


... so you certainly wouldn't write a test that couldn't properly 
determine success or failure.




failed = (result_1 =='KO') or (result_2 =='KO') or (result_3 =='KO') is 
lame but reliable.


In this case I'd write something that meets the specs of the problem 
your addressing...


failed = 'KO' in (result_1,result_2,result_3)

Emile


--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-17 Thread Dr. Phillip M. Feldman

Suppose that 'xor' returns the value that is true when only one value is
true, and False otherwise.  This definition of xor doesn't have the standard
associative property, that is,

(a xor b) xor c

will not necessarily equal

a xor (b xor c)

To see that this is the case, let a= 1, b= 2, and c= 3.

(a xor b) xor c

yields 3, while

a xor (b xor c)

yields 1.  So, I'd prefer an xor operator that simply returns True or False.

Phillip


MRAB-2 wrote:
 
 
 snip
 
 What values should 'xor' return? IMHO, if only one of the values is true
 then it should return that value, otherwise it should return False.
 
  1 xor 0 = 1
  0 xor 2 = 2
  1 xor 2 = False
  0 xor 0 = False
 
 This is because it's a Boolean operator, so it should fall back to
 Boolean values when necessary, like 'not':
 
  not 0 = True
  not 1 = False
 
 Also:
 
  x and y and z = (x and y) and z
  x or y or z = (x or y) or z
 
 therefore:
 
  x xor y xor z = (x xor y) xor z
 -- 
 http://mail.python.org/mailman/listinfo/python-list
 
 

-- 
View this message in context: 
http://www.nabble.com/missing-%27xor%27-Boolean-operator-tp24485116p24543805.html
Sent from the Python - python-list mailing list archive at Nabble.com.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-16 Thread Hendrik van Rooyen
Hrvoje Niksic hnik...@x..s.org wrote:


 Note that in Python A or B is in fact not equivalent to not(not A and
 not B).

De Morgan would turn in his grave.

- Hendrik


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-16 Thread Steven D'Aprano
On Thu, 16 Jul 2009 09:43:53 +0200, Hendrik van Rooyen wrote:

 Hrvoje Niksic hnik...@x..s.org wrote:
 
 
 Note that in Python A or B is in fact not equivalent to not(not A and
 not B).
 
 De Morgan would turn in his grave.

No he wouldn't. Python isn't Boolean algebra, and there is no requirement 
to limit Python's operators to the semantics of Boolean algebra.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-16 Thread Jean-Michel Pichavant

Nobody wrote:

On Wed, 15 Jul 2009 21:05:16 +0200, Jean-Michel Pichavant wrote:

  

So if I resume:
- not 'foo' = False
- 'foo' or 'foo' = 'foo'

I may be missing something, but honestly, Guido must have smoked some 
heavy stuff to write such logic, has he ?



Several languages (e.g. Lisp, Bourne shell) behave the same way, i.e. or
returns the first element which is considered true while and returns the
last element provided that all preceding elements are considered true.
  
[snip]
  


Ok then, why or does not return True, if the first element is 
considered True ? Why returning the element itself. Any reason for that 
? Because it's confusing, maybe people used to that logic find it 
obvious, but I really don't.


JM
--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-16 Thread Anthony Tolle
On Jul 15, 8:32 pm, Paul Rubin http://phr...@nospam.invalid wrote:
 Among other things, that uses quadratic time!  Why do you want to keep
 popping items from that list instead of iterating through it anyway?

 Anyway, I think you wrote something close to this:
 ...

Very true!  I didn't think about the problems with pop().  I was using
it as a shortcut for pulling off the first operand.  I forgot that if
you start with an initial operand of False, the result will be the
same (0 xor X = X)

While I'm not sure how useful it would be, here's a version of the
first function that returns one of the operands (ala AND and OR),
except in the case where there is an even number of True elements,
where it returns False:

def xor(*operands):
r, rprime = False, False
for x in operands:
xprime = bool(x)
if rprime:
if xprime:
r, rprime = False, False
else:
r, rprime = x, xprime
return r

 xor(0, 0)
0
 xor(0, 1)
1
 xor(1, 0)
1
 xor(1, 1)
False
 xor(0, 1, 2)
False
 xor(0, 1, 2, 3)
3
 xor(None, [])
[]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-16 Thread Emile van Sebille

On 7/16/2009 2:06 AM Jean-Michel Pichavant said...
Ok then, why or does not return True, if the first element is 
considered True ? Why returning the element itself. Any reason for that 
? Because it's confusing, maybe people used to that logic find it 
obvious, but I really don't.


For example, I sometimes use it to set defaults:

daysInAdvance = int(inputVar) or 25

Emile

--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-16 Thread Jean-Michel Pichavant

Emile van Sebille wrote:

On 7/16/2009 2:06 AM Jean-Michel Pichavant said...
Ok then, why or does not return True, if the first element is 
considered True ? Why returning the element itself. Any reason for 
that ? Because it's confusing, maybe people used to that logic find 
it obvious, but I really don't.


For example, I sometimes use it to set defaults:

daysInAdvance = int(inputVar) or 25

Emile

Sure this looks like an elegant way to set default values and I will use 
this form , but I'm not sure this justifies by itself the trickery. 
Python has extended the algebra definition of or and and top any 
type, but it is so unintuitive (I'm no LISP programmer). I think than 
using the short-circuiting mechanism of bool operators along with the 
python tricks is just error prone and may result in bug difficult to 
spot, unless you are very aware of all python boolean mechanisms.


JM

--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-16 Thread Grant Edwards
On 2009-07-16, Emile van Sebille em...@fenx.com wrote:
 On 7/16/2009 2:06 AM Jean-Michel Pichavant said...
 Ok then, why or does not return True, if the first element is 
 considered True ? Why returning the element itself. Any reason for that 
 ? Because it's confusing, maybe people used to that logic find it 
 obvious, but I really don't.

 For example, I sometimes use it to set defaults:

 daysInAdvance = int(inputVar) or 25

I don't get it.  That doesn't work right when inputVar == 0.

-- 
Grant Edwards   grante Yow! What I want to find
  at   out is -- do parrots know
   visi.commuch about Astro-Turf?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-16 Thread Emile van Sebille

On 7/16/2009 7:04 AM Unknown said...

On 2009-07-16, Emile van Sebille em...@fenx.com wrote:

daysInAdvance = int(inputVar) or 25


I don't get it.  That doesn't work right when inputVar == 0.

Aah, but you didn't get to define right.  :)  For that particular 
example 0 is not a valid response.


Emile

--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-16 Thread Jean-Michel Pichavant

Emile van Sebille wrote:

On 7/16/2009 7:04 AM Unknown said...

On 2009-07-16, Emile van Sebille em...@fenx.com wrote:

daysInAdvance = int(inputVar) or 25


I don't get it.  That doesn't work right when inputVar == 0.

Aah, but you didn't get to define right.  :)  For that particular 
example 0 is not a valid response.


Emile

When I was talking about such error prone form of boolean operations, I 
didn't expect to be right so quickly :p
Steven explained the truth notion with the Something/Nothing. 0 is 
Something, 0 would be Nothing. I'm not sure it makes sens anyway. I 
mean, I could easily argue that the number 0 is something. In the end I 
wonder if I shouldn't just acknowledge the python mechanism without 
trying to find any intuitive/natural/obvious logic in it, knowing that 
sometimes the Truth lies far away from the Evidence.


JM
--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-16 Thread Luis Alberto Zarrabeitia Gomez

Quoting Jean-Michel Pichavant jeanmic...@sequans.com:

 Emile van Sebille wrote:
  On 7/16/2009 7:04 AM Unknown said...
  On 2009-07-16, Emile van Sebille em...@fenx.com wrote:
  daysInAdvance = int(inputVar) or 25
 
  I don't get it.  That doesn't work right when inputVar == 0.
 
  Aah, but you didn't get to define right.  :)  For that particular 
  example 0 is not a valid response.

 When I was talking about such error prone form of boolean operations, I 
 didn't expect to be right so quickly :p

What do you mean by being right so quickly, and error prone in this context?
I would also ask Unknown why he believes that int(intputVar) or 25 doesn't
work right when inputVar == 0. The only false value that int() may return is
zero, so the or 25 clause is there only for that case. I can't see then how
you think that is an error.

 I'm not sure it makes sens anyway. I 
 mean, I could easily argue that the number 0 is something. In the end I 
 wonder if I shouldn't just acknowledge the python mechanism 

Then look it another way. The Empty/Nothing is just standard practice, there
is nothing in python that forces you to be false if you are empty, or true
otherwise. Instead, answer this: why do you need a /boolean/ value? Is there any
case where you need to be certain that the object's type is 'bool'? If you think
the answer is yes, you may want to get more familiar with the duck typing
concept. (That doesn't mean that there are no legitimate cases where duck typing
is inappropriate, but that there are many cases where people, specially if they
come from statically typed languages, may believe that it is inappropriate when
it isn't).

In the python world, one should care more about how an object /behaves/ than
from what clase it came. If something quacks like a duck, then assume that it is
a duck, at least for the quacking part.

Most python objects carry a truth value. Sometimes it feels natural (None is
false, boolean True and False are true and false, empty containers are
expected to be false, 0 and '' are false). Sometimes, it is everything but
natural, but that's a problem with the object's implementation (datetime.time
comes to mind). So, you shouldn't care if you have a bool instance - it should
be enough that it behaves like a bool (though, if you need a bool, you can
always construct one). The True or False expression could return Giraffes, as
long as Giraffes behave like the bool True in boolean context. If you care
about the class of the result, you can ask for its truth value, and if you don't
care about it, you can just ignore it, and use it as you would use a bool.

And then, if you can return any object as long as it behaves properly, what
would be better to return? A new bool? Why not new Giraffe, if they will have
the same behaviour? Guido chose to return the a value that will say more about
the result of the operation than just a boolean. It acts as a boolean - if you
don't need anything else, treat it as such -, but it will be, whenever is
possible, one of the objects in the sequence, in case you need more info.

 without 
 trying to find any intuitive/natural/obvious logic in it, knowing that 
 sometimes the Truth lies far away from the Evidence.

Don't do that. Many of python's decisions are very well thought. You may
disagree with them, as I do with some, but they are rarely taken lightly. And
this is one that I find very agreeable and in line with the rest of python's
philosophy.

-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie



-- 
Participe en Universidad 2010, del 8 al 12 de febrero de 2010
La Habana, Cuba 
http://www.universidad2010.cu

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-16 Thread Nobody
On Thu, 16 Jul 2009 11:06:54 +0200, Jean-Michel Pichavant wrote:

 So if I resume:
 - not 'foo' = False
 - 'foo' or 'foo' = 'foo'

 I may be missing something, but honestly, Guido must have smoked some 
 heavy stuff to write such logic, has he ?

 Several languages (e.g. Lisp, Bourne shell) behave the same way, i.e. or
 returns the first element which is considered true while and returns the
 last element provided that all preceding elements are considered true.
   
 [snip]
   
 
 Ok then, why or does not return True, if the first element is 
 considered True ?

If the first element is true, returning the first element is returning
true.

 Why returning the element itself. Any reason for that ?

Why not? Where is the benefit in collapsing all true values to True? You
can convert values to True/False with bool(), but the conversion cannot be
reversed.

It only makes a difference if you are interested in the representation
rather than the value. Do you normally test for equality with is or ==?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-16 Thread Nobody
On Wed, 15 Jul 2009 18:14:10 +0200, Hrvoje Niksic wrote:

 If the question was Why is there no 'or' operator ?, would because
 A or B = not(not A and not B) be a proper answer ?
 
 Note that in Python A or B is in fact not equivalent to not(not A and
 not B).

Ah, but it *is* equivalent; it isn't identical, but that's not the
point.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-16 Thread Emile van Sebille

On 7/16/2009 1:29 PM Nobody said...

On Wed, 15 Jul 2009 18:14:10 +0200, Hrvoje Niksic wrote:


If the question was Why is there no 'or' operator ?, would because
A or B = not(not A and not B) be a proper answer ?

Note that in Python A or B is in fact not equivalent to not(not A and
not B).


Ah, but it *is* equivalent; it isn't identical, but that's not the
point.



I'm not sure I'd call it equivalent.  A or B returns either unaltered, 
and not(not A and not B) always returns a boolean.  The equivalent would 
be not(not( A or B )).


Emile

--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-16 Thread Nobody
On Thu, 16 Jul 2009 14:59:22 -0700, Emile van Sebille wrote:

 If the question was Why is there no 'or' operator ?, would because
 A or B = not(not A and not B) be a proper answer ?
 Note that in Python A or B is in fact not equivalent to not(not A and
 not B).
 
 Ah, but it *is* equivalent; it isn't identical, but that's not the
 point.
 
 I'm not sure I'd call it equivalent.

That depends upon what definition of equivalent you are using. Apart
from all manner of vague, informal definitions, there is a formal
definition:

A relation = is an equivalence relation if the following hold for all
x, y, and z:

x = x
x = y = y = x
x = y and y = z = x = z

An equivalence relation partitions its domain into equivalence classes,
such that an element is = (equivalent) to every element in the same
class, and not = to every element in every other class.

This is a lesser notion of equality to identity, which also requires
that x = y = f(x) = f(y) for all f.

Python's notion of boolean values treats x and y as equivalent if
bool(x) == bool(y).

On this basis, the result of A or B is *equivalent* to the result of
not(not A and not B). If you use either result as a boolean value (e.g.
the test of an if or while statement, as an operand to and or or,
etc), the effect is the same. The results aren't *identical*, as there
exist ways to distinguish the two.

As for the utility of this behaviour, returning an actual value rather
than True/False allows the operators to be used as gates. The term
gate in digital logic follows from the axioms: 

0 and x = 0
1 and x = x

0 or x = x
1 or x = 1

[0 = False, 1 = True]

If you consider the left operand as the control and the right operand as
the data, the control determines whether or not the data can pass
through the gate to the output (i.e. whether the gate is open or closed).

In Python:

and:
False and 7 = False
False and 0 = False
True and 7  = 7
True and 0  = 0

or:
False or 7  = 7
False or 0  = 0
True or 7   = True
True or 0   = True


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Tim Roberts
Dr. Phillip M. Feldman pfeld...@verizon.net wrote:

Here's a related issue: I would like to see an option for type checking on
operands of logical operators, so that attempting to apply a logical
operator to non-Boolean entities generates a warning message.  With operand
type checking, 'xor' and != would be different.

How would you define Boolean entities?  Do you mean the True and False
values?  Such a change would break virtually every Python program ever
written.

In any case, this idea is dead in the water.  It would break a whole bunch
of existing code from before the conditional operator:

xxx = testme and truevalue or falsevalue
-- 
Tim Roberts, t...@probo.com
Providenza  Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Mark Dickinson
On Jul 15, 5:07 am, Dr. Phillip M. Feldman pfeld...@verizon.net
wrote:
 I appreciate the effort that people have made, but I'm not impressed with any
 of the answers.  For one thing, xor should be able to accept an arbitrary
 number of input arguments (not just two), and should return True if and only
 if the number of input arguments that evaluate to True is odd.

Well, that's not exactly what you originally asked for.  But it's
still a one-liner:

def xor(*args): return bool(sum(map(bool, args)) % 2)

or perhaps

def xor(*args): return bool(len(filter(None, args))  1)

 Here's my code:

 def xor(*args):
    xor accepts an arbitrary number of input arguments, returning True
    if and only if bool() evaluates to True for an odd number of the input
    arguments.

    result= False

    for arg in args:
       if bool(arg): result= not result

It's more idiomatic to say if arg: ... rather than if bool
(arg): 


    return result

Mark
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Ethan Furman

Scott David Daniels wrote:

Ethan Furman wrote:


  and returns the last object that is true


A little suspect this.
_and_ returns the first object that is not true, or the last object.


  or  returns the first object that is true


Similarly:
_or_ returns the first object that is true, or the last object.



Thanks for the correction.

~Ethan~



--Scott David Daniels
scott.dani...@acm.org


--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Asun Friere
On Jul 15, 5:44 pm, Mark Dickinson dicki...@gmail.com wrote:
 On Jul 15, 5:07 am, Dr. Phillip M. Feldman pfeld...@verizon.net
 wrote:

[snip]

     for arg in args:
        if bool(arg): result= not result

 It's more idiomatic to say if arg: ... rather than if bool
 (arg): 


Ah yes, but not once conditional tests, (just like logical operators),
type-check to ensure they have been supplied with Boolean entities. ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Jonathan Gardner
On Jul 14, 4:48 pm, Ethan Furman et...@stoneleaf.us wrote:

 A whole family of supers.  :)


You should pick up Lisp. The whole concept of a binary operator
doesn't exist over there. All the things binary operators can do, Lisp
does with 0, 1, 2, or more arguments.

[1] (+)
0
[2] (+ 1)
1
[3] (+ 1 2)
3
[4] (+ 1 2 3)
6

Once you get used to that, binary operators don't seem so useful
anymore.

The equivalent in Python is dropping the operators and replacing them
with built-in functions that take 0, 1, 2, or more arguments.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Steven D'Aprano
On Tue, 14 Jul 2009 11:25:08 -0700, Dr. Phillip M. Feldman wrote:

 Current Boolean operators are 'and', 'or', and 'not'.  It would be nice
 to have an 'xor' operator as well.

I've often wished there was too, for the sake of completeness and 
aesthetics, I'd love to be able to write:

a xor b

instead of defining a function xor(a, b).

Unfortunately, outside of boolean algebra and simulating electrical 
circuits, I can't think of any use-cases for an xor operator. Do you have 
any?



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread pdpi
On Jul 15, 12:08 am, Christian Heimes li...@cheimes.de wrote:
 Chris Rebert wrote:
  Using the xor bitwise operator is also an option:
  bool(x) ^ bool(y)

 I prefer something like:

     bool(a) + bool(b) == 1

 It works even for multiple tests (super xor):

   if bool(a) + bool(b) + bool(c) + bool(d) != 1:
       raise ValueError(Exactly one of a, b, c and d must be true)

 Christian

if bool(a) + bool(b) + bool(c) + bool(d) != 1: is not equivalent to
xor. 1 xor 1 xor 1 = 1 xor (1 xor 1) = 1 xor 0 = 1 (or = (1 xor 1) xor
1 = 0 xor 1 = 1 if you assicate to the left)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Tim Wintle

On Wed, 2009-07-15 at 02:02 -0700, Jonathan Gardner wrote:
 On Jul 14, 4:48 pm, Ethan Furman et...@stoneleaf.us wrote:
 
  A whole family of supers.  :)
 
  All the things binary operators can do, Lisp
 does with 0, 1, 2, or more arguments.

+1

n-ary operators are great, but binary operators are just syntactic sugar
for functions (which are obviously a generalisation of an n-ary operator
in python).

The fact that lisp-like languages don't expose this sugar is good for
making you think about what you're actually doing, but just like
mathematicians use binary (and unary) operators in equations rather than
working in the lambda calculus, having that sugar is useful to python.

 
 [1] (+)
 0
 [2] (+ 1)
 1
 [3] (+ 1 2)
 3
 [4] (+ 1 2 3)
 6

c.f. :

 sum([])
0
 sum([1])
1
 sum([1,2])
3
 sum([1,2,3])
6



 Once you get used to that, binary operators don't seem so useful
 anymore.
 
 The equivalent in Python is dropping the operators and replacing them
 with built-in functions that take 0, 1, 2, or more arguments.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Tim Golden

Steven D'Aprano wrote:

On Tue, 14 Jul 2009 11:25:08 -0700, Dr. Phillip M. Feldman wrote:


Current Boolean operators are 'and', 'or', and 'not'.  It would be nice
to have an 'xor' operator as well.


I've often wished there was too, for the sake of completeness and 
aesthetics, I'd love to be able to write:


a xor b

instead of defining a function xor(a, b).

Unfortunately, outside of boolean algebra and simulating electrical 
circuits, I can't think of any use-cases for an xor operator. Do you have 
any?


I was pondering on this yesterday, and the only case I've
come across in my code -- and it's reasonably common --
is checking that one and only one of two params has been
passed. I have code which wants, say, an id or a name
but doesn't want both. It's hardly difficult to write the
check even now, but an built-in xor would make it fractionally
cleaner.

TJG

--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Christian Heimes
pdpi wrote:
 On Jul 15, 12:08 am, Christian Heimes li...@cheimes.de wrote:
 Chris Rebert wrote:
 Using the xor bitwise operator is also an option:
 bool(x) ^ bool(y)
 I prefer something like:

 bool(a) + bool(b) == 1

 It works even for multiple tests (super xor):

   if bool(a) + bool(b) + bool(c) + bool(d) != 1:
   raise ValueError(Exactly one of a, b, c and d must be true)

 Christian
 
 if bool(a) + bool(b) + bool(c) + bool(d) != 1: is not equivalent to
 xor. 1 xor 1 xor 1 = 1 xor (1 xor 1) = 1 xor 0 = 1 (or = (1 xor 1) xor
 1 = 0 xor 1 = 1 if you assicate to the left)

I'm well aware of the fact that I've described something differently.
'xor' can be explained as 'check if exactly one element of two elements
is true'. My algorithms describes a super xor, aka 'check if exactly one
element of n elements is true'.

Christian

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread pdpi
On Jul 15, 12:37 pm, Christian Heimes li...@cheimes.de wrote:
 pdpi wrote:
  On Jul 15, 12:08 am, Christian Heimes li...@cheimes.de wrote:
  Chris Rebert wrote:
  Using the xor bitwise operator is also an option:
  bool(x) ^ bool(y)
  I prefer something like:

      bool(a) + bool(b) == 1

  It works even for multiple tests (super xor):

    if bool(a) + bool(b) + bool(c) + bool(d) != 1:
        raise ValueError(Exactly one of a, b, c and d must be true)

  Christian

  if bool(a) + bool(b) + bool(c) + bool(d) != 1: is not equivalent to
  xor. 1 xor 1 xor 1 = 1 xor (1 xor 1) = 1 xor 0 = 1 (or = (1 xor 1) xor
  1 = 0 xor 1 = 1 if you assicate to the left)

 I'm well aware of the fact that I've described something differently.
 'xor' can be explained as 'check if exactly one element of two elements
 is true'. My algorithms describes a super xor, aka 'check if exactly one
 element of n elements is true'.

 Christian

Well, I just wouldn't call it a super xor then, when unicity test
works much better -- especially as an alternative to an actual xor
without any specification to the actual intended functionality except
the exception text.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Bill Davy
MRAB pyt...@mrabarnett.plus.com wrote in message 
news:mailman.3158.1247667680.8015.python-l...@python.org...
 Steven D'Aprano wrote:
 On Tue, 14 Jul 2009 11:25:08 -0700, Dr. Phillip M. Feldman wrote:

 Current Boolean operators are 'and', 'or', and 'not'.  It would be nice
 to have an 'xor' operator as well.

 I've often wished there was too, for the sake of completeness and 
 aesthetics, I'd love to be able to write:

 a xor b

 instead of defining a function xor(a, b).

 Unfortunately, outside of boolean algebra and simulating electrical 
 circuits, I can't think of any use-cases for an xor operator. Do you have 
 any?

 The problem is that 'and' and 'or' are not limited to Boolean values:

 'and' returns the first false value or the last true value.

 'or' returns the first true value or the last false value.

 What values should 'xor' return? IMHO, if only one of the values is true
 then it should return that value, otherwise it should return False.

 1 xor 0 = 1
 0 xor 2 = 2
 1 xor 2 = False
 0 xor 0 = False

 This is because it's a Boolean operator, so it should fall back to
 Boolean values when necessary, like 'not':

 not 0 = True
 not 1 = False

 Also:

 x and y and z = (x and y) and z
 x or y or z = (x or y) or z

 therefore:

 x xor y xor z = (x xor y) xor z


Gosh, let's all discuss commutation and distribution.

And surely in quantum merchanics there is something about non-commuting 
operatiomns letting in Planck's constant. 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Jean-Michel Pichavant

Christian Heimes wrote:

Chris Rebert wrote:
  

Using the xor bitwise operator is also an option:
bool(x) ^ bool(y)



I prefer something like:

bool(a) + bool(b) == 1

It works even for multiple tests (super xor):

  if bool(a) + bool(b) + bool(c) + bool(d) != 1:
  raise ValueError(Exactly one of a, b, c and d must be true)

Christian

  
While everyone's trying to tell the OP how to workaround the missing xor 
operator, nobody answered the question why is there no xor operator ?.


If the question was Why is there no 'or' operator ?, would because A 
or B = not(not A and not B) be a proper answer ?


JM

--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Robert Kern

On 2009-07-15 10:15, Jean-Michel Pichavant wrote:

Christian Heimes wrote:

Chris Rebert wrote:

Using the xor bitwise operator is also an option:
bool(x) ^ bool(y)


I prefer something like:

bool(a) + bool(b) == 1

It works even for multiple tests (super xor):

if bool(a) + bool(b) + bool(c) + bool(d) != 1:
raise ValueError(Exactly one of a, b, c and d must be true)

Christian


While everyone's trying to tell the OP how to workaround the missing xor
operator, nobody answered the question why is there no xor operator ?.

If the question was Why is there no 'or' operator ?, would because A
or B = not(not A and not B) be a proper answer ?


That's not the only answer the OP has been given. The most compelling answer is 
that an xor keyword cannot be implemented with similar semantics to and and 
or, in particular short-circuiting and returning one of the actual inputs 
instead of a coerced bool.


--
Robert Kern

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Hrvoje Niksic
Jean-Michel Pichavant jeanmic...@sequans.com writes:

 While everyone's trying to tell the OP how to workaround the missing
 xor operator, nobody answered the question why is there no [boolean]
 xor operator ?.

Probably because there isn't one in C.  The bitwise XOR operator, on the
other hand, exists in both C and Python.

 If the question was Why is there no 'or' operator ?, would because
 A or B = not(not A and not B) be a proper answer ?

Note that in Python A or B is in fact not equivalent to not(not A and
not B).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Paul Rubin
Hrvoje Niksic hnik...@xemacs.org writes:
  While everyone's trying to tell the OP how to workaround the missing
  xor operator, nobody answered the question why is there no [boolean]
  xor operator ?.
 
 Probably because there isn't one in C.  The bitwise XOR operator, on the
 other hand, exists in both C and Python.

A non-bitwise XOR really sounds almost useless.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Wayne Brehaut
On Wed, 15 Jul 2009 13:37:22 +0200, Christian Heimes
li...@cheimes.de wrote:

pdpi wrote:
 On Jul 15, 12:08 am, Christian Heimes li...@cheimes.de wrote:
 Chris Rebert wrote:
 Using the xor bitwise operator is also an option:
 bool(x) ^ bool(y)
 I prefer something like:

 bool(a) + bool(b) == 1

 It works even for multiple tests (super xor):

   if bool(a) + bool(b) + bool(c) + bool(d) != 1:
   raise ValueError(Exactly one of a, b, c and d must be true)

 Christian
 
 if bool(a) + bool(b) + bool(c) + bool(d) != 1: is not equivalent to
 xor. 1 xor 1 xor 1 = 1 xor (1 xor 1) = 1 xor 0 = 1 (or = (1 xor 1) xor
 1 = 0 xor 1 = 1 if you assicate to the left)

I'm well aware of the fact that I've described something differently.
'xor' can be explained as 'check if exactly one element of two elements
is true'. My algorithms describes a super xor, aka 'check if exactly one
element of n elements is true'.

But that's not a super xor (commonly known as XOR). Rather than
describing xor as:

check if exactly one element of two elements is true

describe it as:

check if an odd number of two elements is true

then you'll get the correct definition of super xor:

check if an odd number of n elements is true

I.e., XOR determines parity, and:

XOR some binary vector v =
0 if v has an even number of 1s and 
1 if v has an odd number of 1s

wayne

Christian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Jean-Michel Pichavant

Hrvoje Niksic wrote:
[snip]

Note that in Python A or B is in fact not equivalent to not(not A and
not B).
  

 l = [(True, True), (True, False), (False, True), (False, False)]
 for p in l:
... p[0] or p[1]
...
True
True
True
False
 for p in l:
... not(not p[0] and not p[1])
...
True
True
True
False
  


Did I make twice the same obvious error ?

JM
--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Emile van Sebille

On 7/15/2009 10:43 AM Jean-Michel Pichavant said...

Hrvoje Niksic wrote:
[snip]

Note that in Python A or B is in fact not equivalent to not(not A and
not B).
  

  l = [(True, True), (True, False), (False, True), (False, False)]
  for p in l:
... p[0] or p[1]
...
True
True
True
False
  for p in l:
... not(not p[0] and not p[1])
...
True
True
True
False
  
Did I make twice the same obvious error ?


No -- but in the not(not... example it doesn't short-circuit.

Emile

--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Miles Kaufmann


On Jul 15, 2009, at 1:43 PM, Jean-Michel Pichavant wrote:


Hrvoje Niksic wrote:
[snip]

Note that in Python A or B is in fact not equivalent to not(not A and
not B).


 l = [(True, True), (True, False), (False, True), (False, False)]
 for p in l:
... p[0] or p[1]
[snip]
Did I make twice the same obvious error ?



Try again with:

l = [('foo','bar'), ('foo', ''), ('', 'bar'), ('', '')]

-Miles

--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Miles Kaufmann

On Jul 15, 2009, at 1:55 PM, Emile van Sebille wrote:

On 7/15/2009 10:43 AM Jean-Michel Pichavant said...

Hrvoje Niksic wrote:
[snip]
Note that in Python A or B is in fact not equivalent to not(not A  
and

not B).


Did I make twice the same obvious error ?


No -- but in the not(not... example it doesn't short-circuit.


No; like 'A or B', 'not (not A and not B)' does in fact short-circuit  
if A is True.  (The 'and' condition does not have to evaluate the  
right operand when 'not A' is False.)


-Miles

--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Terry Reedy

Tim Golden wrote:


I was pondering on this yesterday, and the only case I've
come across in my code -- and it's reasonably common --
is checking that one and only one of two params has been
passed. I have code which wants, say, an id or a name
but doesn't want both. It's hardly difficult to write the
check even now, but an built-in xor would make it fractionally
cleaner.


I think I would just have one parameter id_name or identifier so no 
check is needed. This is a common idiom in Python where names are not 
typed. Example: param 'source' is a string (with a file name to be 
opened) or an already opened file. If you want two local vars inside the 
function, that should be kept private to the function.


tjr

--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Dr. Phillip M. Feldman

I did initially ask for an infix xor operator, but eventually gave up on
this.  I like the first of your two one-line solutions below; this is clean
and easy to understand.  Thanks!  I'd still like to be able to write an
expression like '(a and b) xor (c and d) xor (e and f)', but it looks as
though that can't be done.



snip

Well, that's not exactly what you originally asked for.  But it's
still a one-liner:

def xor(*args): return bool(sum(map(bool, args)) % 2)

or perhaps

def xor(*args): return bool(len(filter(None, args))  1)
-- 
View this message in context: 
http://www.nabble.com/missing-%27xor%27-Boolean-operator-tp24485116p24503248.html
Sent from the Python - python-list mailing list archive at Nabble.com.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Wayne Brehaut
On Tue, 14 Jul 2009 11:47:41 -0700 (PDT), Mark Dickinson
dicki...@gmail.com wrote:

On Jul 14, 7:25 pm, Dr. Phillip M. Feldman pfeld...@verizon.net
wrote:
 Current Boolean operators are 'and', 'or', and 'not'.  It would be nice to
 have an 'xor' operator as well.

Hmm.  I don't think 'nice' is sufficient.  You'd need to make the case
that it's sufficiently useful to justify adding a new keyword 'xor' to
the language;  I suspect that would be an uphill struggle. :)

I'll just note that:

(1) It's easy to emulate xor:  'x xor y' - bool(x) != bool(y)

(2) 'and' and 'or' are special in that they have useful short-
circuiting behaviour; xor doesn't have this property (that is, you
always need to evaluate *both* operands to determine the result).

I'd also guess that 'xor' would be much less used than 'and' or 'or',
but maybe that's just a reflection of the sort of code that I tend to
write.

You're right about that!. It's used everywhere in:

- coding and encryption theory (and practice) (e.g.,
http://www.mathcs.emory.edu/~whalen/Hash/Hash_Articles/IEEE/XOR-based%20hash%20functions.pdf)
- emulation and simulation of hardware (since all but the most trivial
logic circuits are likely to include XOR-gates)
- hence, for design of new architectures or simulators or virtual
machines and simplification of existing ones--(e.g.,
http://www.date-conference.com/archive/conference/proceedings/PAPERS/1999/DATE99/PDFFILES/05A_6.PDF)
and
http://bochs.sourceforge.net/Virtualization_Without_Hardware_Final.pdf
which includes:

The answer relies on the observation that subtracting an integer
value from 0x gives the same result as XOR-ing that same value
to 0x.

And, perhaps the most useful use of all, for Bouton's solution of the
game of Nim--both for the proof that his strategy solves the game
and for an easy implementation of a Nim-playing program--and the only
operator needed is XOR (e.g., http://www.wordiq.com/definition/Nim).

wayne
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Robert Kern

On 2009-07-15 13:29, Wayne Brehaut wrote:

On Tue, 14 Jul 2009 11:47:41 -0700 (PDT), Mark Dickinson
dicki...@gmail.com  wrote:


On Jul 14, 7:25 pm, Dr. Phillip M. Feldmanpfeld...@verizon.net
wrote:

Current Boolean operators are 'and', 'or', and 'not'.  It would be nice to
have an 'xor' operator as well.

Hmm.  I don't think 'nice' is sufficient.  You'd need to make the case
that it's sufficiently useful to justify adding a new keyword 'xor' to
the language;  I suspect that would be an uphill struggle. :)

I'll just note that:

(1) It's easy to emulate xor:  'x xor y'-  bool(x) != bool(y)

(2) 'and' and 'or' are special in that they have useful short-
circuiting behaviour; xor doesn't have this property (that is, you
always need to evaluate *both* operands to determine the result).

I'd also guess that 'xor' would be much less used than 'and' or 'or',
but maybe that's just a reflection of the sort of code that I tend to
write.


You're right about that!. It's used everywhere in:

- coding and encryption theory (and practice) (e.g.,
http://www.mathcs.emory.edu/~whalen/Hash/Hash_Articles/IEEE/XOR-based%20hash%20functions.pdf)
- emulation and simulation of hardware (since all but the most trivial
logic circuits are likely to include XOR-gates)
- hence, for design of new architectures or simulators or virtual
machines and simplification of existing ones--(e.g.,
http://www.date-conference.com/archive/conference/proceedings/PAPERS/1999/DATE99/PDFFILES/05A_6.PDF)
and
http://bochs.sourceforge.net/Virtualization_Without_Hardware_Final.pdf
which includes:

The answer relies on the observation that subtracting an integer
value from 0x gives the same result as XOR-ing that same value
to 0x.

And, perhaps the most useful use of all, for Bouton's solution of the
game of Nim--both for the proof that his strategy solves the game
and for an easy implementation of a Nim-playing program--and the only
operator needed is XOR (e.g., http://www.wordiq.com/definition/Nim).


All of those can use the bitwise XOR operator, not the boolean XOR. Python 
already has the ^ operator for those purposes.


--
Robert Kern

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Mark Dickinson
On Jul 15, 7:29 pm, Wayne Brehaut wbreh...@mcsnet.ca wrote:
 On Tue, 14 Jul 2009 11:47:41 -0700 (PDT), Mark Dickinson dicki...@gmail.com 
 wrote:
 I'd also guess that 'xor' would be much less used than 'and' or 'or',
 but maybe that's just a reflection of the sort of code that I tend to
 write.

 You're right about that!. It's used everywhere in:
 [snip examples and references]

Those examples are (almost) all about the *bitwise* xor operator,
which exists in Python ('^') and, as you point out, has no shortage of
good uses.  The discussion was about a *logical* xor, to parallel the
existing 'and' and 'or' operators.

--
Mark
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Anthony Tolle
On Jul 14, 2:25 pm, Dr. Phillip M. Feldman pfeld...@verizon.net
wrote:
 Current Boolean operators are 'and', 'or', and 'not'.  It would be nice to
 have an 'xor' operator as well.

My $0.02 on this discussion: There would be nothing gained by having
non-bitwise XOR operator.  You can't short-circuit XOR, because you
must evaluate all operands to produce a result.  Consequently,
returning the true item also doesn't make much sense.  XOR is closer
to the the logical NOT operator than it is to AND or OR.

Here's my own take on a function that can handle any number of
arguments (it should probably raise an exception for 0 or 1 arguments,
but I'm lazy):

def xor(*operands):
if operands:
operands = list(operands)
a = bool(operands.pop(0))
while operands:
b = bool(operands.pop(0))
if a:
if b:
a = False
elif b:
a = True
return a
return False
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Jean-Michel Pichavant

Miles Kaufmann wrote:


On Jul 15, 2009, at 1:43 PM, Jean-Michel Pichavant wrote:


Hrvoje Niksic wrote:
[snip]

Note that in Python A or B is in fact not equivalent to not(not A and
not B).


 l = [(True, True), (True, False), (False, True), (False, False)]
 for p in l:
... p[0] or p[1]
[snip]
Did I make twice the same obvious error ?



Try again with:

l = [('foo','bar'), ('foo', ''), ('', 'bar'), ('', '')]

-Miles


Didn't know that.
So if I resume:
- not 'foo' = False
- 'foo' or 'foo' = 'foo'

I may be missing something, but honestly, Guido must have smoked some 
heavy stuff to write such logic, has he ?


Let's play again
False or 'foo' = 'foo'
False and 'foo' = False

So funny. I would have expected boolean operators to return a boolean 
value. I should have read the f*** manual (this is an anticipated RTFM 
counter-attack). Anyway Miles, thanks for the update.


JM

--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Wayne Brehaut
On Wed, 15 Jul 2009 11:51:44 -0700 (PDT), Mark Dickinson
dicki...@gmail.com wrote:

On Jul 15, 7:29 pm, Wayne Brehaut wbreh...@mcsnet.ca wrote:
 On Tue, 14 Jul 2009 11:47:41 -0700 (PDT), Mark Dickinson 
 dicki...@gmail.com wrote:
 I'd also guess that 'xor' would be much less used than 'and' or 'or',
 but maybe that's just a reflection of the sort of code that I tend to
 write.

 You're right about that!. It's used everywhere in:
 [snip examples and references]

Those examples are (almost) all about the *bitwise* xor operator,
which exists in Python ('^') and, as you point out, has no shortage of
good uses.  The discussion was about a *logical* xor, to parallel the
existing 'and' and 'or' operators.

I thought you were saying your program domains didn't include a lot of
requirements for xor in general, rather than just no uses for Boolean
xor--and I'm used to thinking of xor on binary vectors as Boolean
anyway so would still have been confused.

The most common non-binary-bit-wise xor is the general symmetric
difference of sets, most likely to be useful in list or dictionary
processing or database-like contexts. Please see my suggested use-case
for Steven below.

wayne
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Hrvoje Niksic
Jean-Michel Pichavant jeanmic...@sequans.com writes:

 Hrvoje Niksic wrote:
 [snip]
 Note that in Python A or B is in fact not equivalent to not(not A and
 not B).
   
 l = [(True, True), (True, False), (False, True), (False, False)]
 for p in l:
 ... p[0] or p[1]
[...]

Try with a different data set, for example:

 10 or 20
10
 not(not 10 and not 20)
True
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Wayne Brehaut
On Tue, 14 Jul 2009 11:47:41 -0700 (PDT), Mark Dickinson
dicki...@gmail.com wrote:

On Jul 14, 7:25 pm, Dr. Phillip M. Feldman pfeld...@verizon.net
wrote:
 Current Boolean operators are 'and', 'or', and 'not'.  It would be nice to
 have an 'xor' operator as well.

Hmm.  I don't think 'nice' is sufficient.  You'd need to make the case
that it's sufficiently useful to justify adding a new keyword 'xor' to
the language;  I suspect that would be an uphill struggle. :)

=== 8 ===
And for the objects for which it *is* sufficiently useful (sets) the
xor operator ^ is available:

 cheese = set(['cheddar', 'limburger', 'stilton'])
 stinky = set(['skunk', 'limburger', 'stilton', 'polecat', 'doggy-doo', 
 'civet'])
 nasty = set(['doggy-doo', 'polecat', 'limburger', 'Perl'])
 cheese  stinky # stinky cheese
set(['limburger', 'stilton'])
 cheese ^ stinky # either cheese or stinky but not both
set(['doggy-doo', 'civet', 'polecat', 'skunk', 'cheddar'])
 cheese ^ stinky ^ nasty # in an odd number of these sets (1 or 3)
set(['civet', 'cheddar', 'Perl', 'limburger', 'skunk'])

wayne
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Wayne Brehaut
On 15 Jul 2009 09:11:44 GMT, Steven D'Aprano
ste...@remove.this.cybersource.com.au wrote:

On Tue, 14 Jul 2009 11:25:08 -0700, Dr. Phillip M. Feldman wrote:

 Current Boolean operators are 'and', 'or', and 'not'.  It would be nice
 to have an 'xor' operator as well.

I've often wished there was too, for the sake of completeness and 
aesthetics, I'd love to be able to write:

a xor b

instead of defining a function xor(a, b).

Unfortunately, outside of boolean algebra and simulating electrical 
circuits, I can't think of any use-cases for an xor operator. Do you have 
any?

Since xor in set theory is the symmetric difference,  perhaps we'd
like to know all items in exactly one of two word lists or
dictionaries, or anything else we could easily set-ize:

 cheese = set(['cheddar', 'limburger', 'stilton'])
 stinky = set(['skunk', 'limburger', 'stilton', 'polecat', 'doggy-doo', 
 'civet'])
 nasty = set(['doggy-doo', 'polecat', 'limburger', 'Perl'])
 cheese  stinky # stinky cheese
set(['limburger', 'stilton'])
 cheese ^ stinky # either cheese or stinky but not both
set(['doggy-doo', 'civet', 'polecat', 'skunk', 'cheddar'])
 cheese ^ stinky ^ nasty # in an odd number of these sets (1 or 3)
set(['civet', 'cheddar', 'Perl', 'limburger', 'skunk'])

Who hasn't needed that occasionally?

wayne
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Chris Rebert
On Wed, Jul 15, 2009 at 3:57 PM, Wayne Brehautwbreh...@mcsnet.ca wrote:
 On 15 Jul 2009 09:11:44 GMT, Steven D'Aprano
 ste...@remove.this.cybersource.com.au wrote:

On Tue, 14 Jul 2009 11:25:08 -0700, Dr. Phillip M. Feldman wrote:

 Current Boolean operators are 'and', 'or', and 'not'.  It would be nice
 to have an 'xor' operator as well.

I've often wished there was too, for the sake of completeness and
aesthetics, I'd love to be able to write:

a xor b

instead of defining a function xor(a, b).

Unfortunately, outside of boolean algebra and simulating electrical
circuits, I can't think of any use-cases for an xor operator. Do you have
any?

 Since xor in set theory is the symmetric difference,  perhaps we'd
 like to know all items in exactly one of two word lists or
 dictionaries, or anything else we could easily set-ize:

 cheese = set(['cheddar', 'limburger', 'stilton'])
 stinky = set(['skunk', 'limburger', 'stilton', 'polecat', 'doggy-doo', 
 'civet'])
 nasty = set(['doggy-doo', 'polecat', 'limburger', 'Perl'])
 cheese  stinky # stinky cheese
 set(['limburger', 'stilton'])
 cheese ^ stinky # either cheese or stinky but not both
 set(['doggy-doo', 'civet', 'polecat', 'skunk', 'cheddar'])
 cheese ^ stinky ^ nasty # in an odd number of these sets (1 or 3)
 set(['civet', 'cheddar', 'Perl', 'limburger', 'skunk'])

 Who hasn't needed that occasionally?

This discussion is about adding a *logical* operator for use in
boolean expressions. We obviously already have ^ for non-boolean use.

Cheers,
Chris
-- 
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Nobody
On Wed, 15 Jul 2009 21:05:16 +0200, Jean-Michel Pichavant wrote:

 So if I resume:
 - not 'foo' = False
 - 'foo' or 'foo' = 'foo'
 
 I may be missing something, but honestly, Guido must have smoked some 
 heavy stuff to write such logic, has he ?

Several languages (e.g. Lisp, Bourne shell) behave the same way, i.e. or
returns the first element which is considered true while and returns the
last element provided that all preceding elements are considered true.

 Let's play again
 False or 'foo' = 'foo'
 False and 'foo' = False
 
 So funny. I would have expected boolean operators to return a boolean 
 value.

In Python, almost everything is a boolean value.

Compare with Lisp, where everything is a boolean value: nil (the empty
list) is false and everything else (including integer zero) is true.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Paul Rubin
Anthony Tolle anthony.to...@gmail.com writes:
 def xor(*operands):
 if operands:
 operands = list(operands)
 a = bool(operands.pop(0))
 while operands:
 b = bool(operands.pop(0))
 if a:
 if b:
 a = False
 elif b:
 a = True
 return a
 return False

Among other things, that uses quadratic time!  Why do you want to keep
popping items from that list instead of iterating through it anyway?

Anyway, I think you wrote something close to this:

def xor(*operands):
   r = False
   for x in operands:
  r = (r != bool(x))
   return r

or in map-reduce style:

from operator import ne
def xor(*operands):
   return reduce(ne, map(bool, operands), False)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Steven D'Aprano
On Wed, 15 Jul 2009 21:05:16 +0200, Jean-Michel Pichavant wrote:

 Didn't know that.
 So if I resume:
 - not 'foo' = False
 - 'foo' or 'foo' = 'foo'
 
 I may be missing something, but honestly, Guido must have smoked some
 heavy stuff to write such logic, has he ?

No, it's perfectly reasonable, and not at all the product of mind-
altering drugs. Other languages do the same thing.


for x in alist or blist or clist:
print x

will select the first non-empty list and iterate over that.



Every object in Python has a truth value. By convention, we say that 
objects are Something or Nothing.

0 None [] '' are examples of Nothing, or false values.

1 2.5 [x, y, z] 'foo' are examples of Something, or true values.

Note the distinction between lower-case false and true (adjectives), 
and title-case False and True (nouns).


`if x: ... else:` branches according to whether x is Something or 
Nothing, not whether it is True or False.

The operators `and` and `or` also return Something or Nothing, short-
circuiting as appropriate.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-14 Thread Chris Rebert
On Tue, Jul 14, 2009 at 11:47 AM, Mark Dickinsondicki...@gmail.com wrote:
 On Jul 14, 7:25 pm, Dr. Phillip M. Feldman pfeld...@verizon.net
 wrote:
 Current Boolean operators are 'and', 'or', and 'not'.  It would be nice to
 have an 'xor' operator as well.

 Hmm.  I don't think 'nice' is sufficient.  You'd need to make the case
 that it's sufficiently useful to justify adding a new keyword 'xor' to
 the language;  I suspect that would be an uphill struggle. :)

 I'll just note that:

 (1) It's easy to emulate xor:  'x xor y' - bool(x) != bool(y)

Using the xor bitwise operator is also an option:
bool(x) ^ bool(y)

Cheers,
Chris
-- 
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-14 Thread Ethan Furman

Robert Kern wrote:

On 2009-07-14 14:56, Dr. Phillip M. Feldman wrote:

!= does do what I want, except that it doesn't indicate to someone 
reading
the code that the operands are being treated as logicals.  
(Readability is

supposed to be one of the major selling points of Python).  But, this is
probably good enough.



In the words of those greater than myself, Not every one-liner needs to 
be in the standard library.


def xor(a, b):
return bool(a) != bool(b)



Let's see...

  and returns the last object that is true
  or  returns the first object that is true

so should xor return the only object that is true, else False/None?

def xor(a, b)
if a and b:
return None
elif a:
return a
elif b:
return b
else:
return None

~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-14 Thread MRAB

Ethan Furman wrote:

Robert Kern wrote:

On 2009-07-14 14:56, Dr. Phillip M. Feldman wrote:

!= does do what I want, except that it doesn't indicate to someone 
reading
the code that the operands are being treated as logicals.  
(Readability is

supposed to be one of the major selling points of Python).  But, this is
probably good enough.



In the words of those greater than myself, Not every one-liner needs 
to be in the standard library.


def xor(a, b):
return bool(a) != bool(b)



Let's see...

  and returns the last object that is true
  or  returns the first object that is true

so should xor return the only object that is true, else False/None?

def xor(a, b)
if a and b:
return None
elif a:
return a
elif b:
return b
else:
return None


How about:

def xor(a, b):
return not b and a or not a and b
--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-14 Thread Ethan Furman

MRAB wrote:

Ethan Furman wrote:


Robert Kern wrote:


On 2009-07-14 14:56, Dr. Phillip M. Feldman wrote:

!= does do what I want, except that it doesn't indicate to someone 
reading
the code that the operands are being treated as logicals.  
(Readability is
supposed to be one of the major selling points of Python).  But, 
this is

probably good enough.




In the words of those greater than myself, Not every one-liner needs 
to be in the standard library.


def xor(a, b):
return bool(a) != bool(b)



Let's see...

  and returns the last object that is true
  or  returns the first object that is true

so should xor return the only object that is true, else False/None?

def xor(a, b)
if a and b:
return None
elif a:
return a
elif b:
return b
else:
return None


How about:

def xor(a, b):
return not b and a or not a and b


In [12]: not 1 and 0 or 1 and not 0
Out[12]: True

In [13]: not 0 and 0 or 0 and not 0
Out[13]: 0

In [14]: not 1 and 1 or 1 and not 1
Out[14]: False

In [15]: not [] and [] or [] and not []
Out[15]: []

Doesn't produce consistent objects, sometimes bool, sometimes something 
else.  'Course, it all depends on what you need.


~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-14 Thread Christian Heimes
Chris Rebert wrote:
 Using the xor bitwise operator is also an option:
 bool(x) ^ bool(y)

I prefer something like:

bool(a) + bool(b) == 1

It works even for multiple tests (super xor):

  if bool(a) + bool(b) + bool(c) + bool(d) != 1:
  raise ValueError(Exactly one of a, b, c and d must be true)

Christian

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-14 Thread Scott David Daniels

Ethan Furman wrote:

  and returns the last object that is true

A little suspect this.
_and_ returns the first object that is not true, or the last object.

  or  returns the first object that is true

Similarly:
_or_ returns the first object that is true, or the last object.


so should xor return the only object that is true, else False/None?


Xor has the problem that in two cases it can return neither of its args.
Not has behavior similar in those cases, and we see it returns False or
True.  The Pythonic solution is therefore to use False.


def xor(a, b)
if a and b:
return None
elif a:
return a
elif b:
return b
else:
return None


def xor(a, b):
if bool(a) == bool(b):
return False
else:
return a or b

Side-effect counting in applications of bool(x) is ignored here.
If minimizing side-effects is needed:

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

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-14 Thread Ethan Furman

Christian Heimes wrote:

Chris Rebert wrote:


Using the xor bitwise operator is also an option:
bool(x) ^ bool(y)



I prefer something like:

bool(a) + bool(b) == 1

It works even for multiple tests (super xor):

  if bool(a) + bool(b) + bool(c) + bool(d) != 1:
  raise ValueError(Exactly one of a, b, c and d must be true)

Christian



super_xor!  I like it!

In [23]: def super_xor(args, failure=False):
   : found_one = False
   : for item in args:
   : if item:
   : if found_one:
   : return failure
   : else:
   : found_one = item
   : return found_one or failure

In [25]: super_xor((0, 1, 0, []))
Out[25]: 1

In [26]: super_xor((0, 1, 0, [],('this',)))
Out[26]: False

In [27]: super_xor((0, {}, 0, [],()))
Out[27]: False

In [16]: def super_or(args, failure=False):
   : for item in args:
   : if item:
   : return item
   : else:
   : return failure
   :

In [17]: super_or((None, [], 0, 3, {}))
Out[17]: 3

In [18]: super_or((None, [], 0, (), {}))
Out[18]: False

In [19]: def super_and(args, failure=False):
   : for item in args:
   : if not item:
   : return failure
   : else:
   : return item
   :

In [20]: super_and((1, 2, 3))
Out[20]: 3

In [21]: super_and((1, 2, 3, 4))
Out[21]: 4

In [22]: super_and((1, 0, 3, 4))
Out[22]: False

A whole family of supers.  :)

~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-14 Thread Dr. Phillip M. Feldman

I appreciate the effort that people have made, but I'm not impressed with any
of the answers.  For one thing, xor should be able to accept an arbitrary
number of input arguments (not just two), and should return True if and only
if the number of input arguments that evaluate to True is odd (see
www.mathworld.com article on xor).  Here's my code:

def xor(*args):
   xor accepts an arbitrary number of input arguments, returning True
   if and only if bool() evaluates to True for an odd number of the input
   arguments.

   result= False

   for arg in args:
  if bool(arg): result= not result

   return result



MRAB-2 wrote:
 
 Ethan Furman wrote:
 Robert Kern wrote:
 On 2009-07-14 14:56, Dr. Phillip M. Feldman wrote:

 != does do what I want, except that it doesn't indicate to someone 
 reading
 the code that the operands are being treated as logicals.  
 (Readability is
 supposed to be one of the major selling points of Python).  But, this
 is
 probably good enough.


 In the words of those greater than myself, Not every one-liner needs 
 to be in the standard library.

 def xor(a, b):
 return bool(a) != bool(b)

 
 Let's see...
 
   and returns the last object that is true
   or  returns the first object that is true
 
 so should xor return the only object that is true, else False/None?
 
 def xor(a, b)
 if a and b:
 return None
 elif a:
 return a
 elif b:
 return b
 else:
 return None
 
 How about:
 
 def xor(a, b):
  return not b and a or not a and b
 -- 
 http://mail.python.org/mailman/listinfo/python-list
 
 

-- 
View this message in context: 
http://www.nabble.com/missing-%27xor%27-Boolean-operator-tp24485116p24491580.html
Sent from the Python - python-list mailing list archive at Nabble.com.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-14 Thread Miles Kaufmann

On Jul 15, 2009, at 12:07 AM, Dr. Phillip M. Feldman wrote:

I appreciate the effort that people have made, but I'm not impressed  
with any
of the answers.  For one thing, xor should be able to accept an  
arbitrary

number of input arguments (not just two)


You originally proposed this in the context of the existing short- 
circuit boolean operators.  Those operators (being infix) take only  
two operands.



and should return True if and only
if the number of input arguments that evaluate to True is odd


The existing and/or operators always return the value of one of the  
operands--not necessarily True or False--which is another important  
property, but one that can't be translated fully to xor.  Given the  
lack of context in your original post, hopefully you'll forgive me  
being unimpressed by your not being impressed. :)



Here's my code:

def xor(*args):
  xor accepts an arbitrary number of input arguments, returning  
True
  if and only if bool() evaluates to True for an odd number of the  
input

  arguments.

  result= False

  for arg in args:
 if bool(arg): result= not result

  return result


If all you want is a True or False result, I'd write it like this:

import operator
def xor(*args):
return reduce(operator.xor, map(bool, args)) # or imap

In order to make it act more like the other logical operators, I'd use  
MRAB's 2-argument xor as the reducer--though I can't really see the  
utility.


def xor2(a, b):
return (not b and a) or (not a and b)

def xor(*args):
return reduce(xor2, args)

You may also find this question interesting:

http://stackoverflow.com/questions/432842/

-Miles

--
http://mail.python.org/mailman/listinfo/python-list