[Baypiggies] Baypiggies snippets
aleax at google.com
Thu Mar 22 18:15:38 CET 2007
On 3/22/07, Stephen McInerney <spmcinerney at hotmail.com> wrote:
> Monte, about this nested compare "a <= x <= b"
> Q1: Since what version has it been in? I never knew about it!
I was there in 1.5 when I got started with Python; I believe it's quite old.
Q2: Can anyone comment on the efficiency of
> "a <= x <= b" vs "x in xrange(a,b)" (obviously the latter is worse, and
> good for integer a,b)
> In particular, is Python smart enough to binary-search the xrange object?
> Just curious.
Type 'xrange' does not even define a __contains__ method. I wonder how a
patch implementing one would be seen by python-dev; I'm pretty sure it would
be rejected if it tried to use binary search, though (why take O(log N) time
if you're going to the trouble of implementing __contains__ when it
obviously can be done in O(1) time?).
Q3: C++ people would balk at the idiom "a <= x <= b"
> since it does not evaluate right-to-left. (The two <= subexpressions
> cannot be separately evaluated from the other. So it has to be
> parsed and evaluated all in one)
??? comparison chaining short-circuits, so OF COURSE a and b ARE
"separately evaluated"! E.g:
>>> 23 < 15 < (7/0)
the 7/0 is NOT attempted (it would raise if it were) -- no need, because the
23 < 15 check has already failed.
In C++, a && b && c would similarly be evaluated left-to-right, with
short-circuiting, so I don't see what objections there could be.
Short-circuiting operators (&& and || in C and C++, and, or and comparison
chaining in Python) always go left-to-right.
Q4: are the idioms "a == x == b", "a != x != b" and "a is x is b" legal?
Yep, chaining applies to all comparison operators, including ==, !=, is, and
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Baypiggies