blessed be Guido, for "5 <= X <= 10" does what it should...

Warren Postma embed at geocities.com
Tue Apr 4 14:42:41 EDT 2000


<X-DISCLAIMER: I'm in a weird mood.>

I was just playing around today,and it occurred to me to test the
'transitive' properties of comparison operators. Ie, writing on a
chalkboard, you might say X is in the range 5..9 this way:

        5 <= X <= 9

(Actually I'd write the <= as '?' (Unicode U+2264) but using such things in
our code would seriously cramp portability.  Hey, is the APL symbol set
anywhere in Unicode!?)

In some programming languages, which reduce each comparison to a boolean
True or False, using the precedence rules, the result is:

        n = (5<=X)
        n <= 9

Since 'n' is probably 0 or 1 (commodore 64 basic used -1 for true, remember
that?) anywyas, 'n' is always <= 9, which means the whole expression is
always false.

If precedence rules were right to left:
        n = (X<=9)
        5 <= n

In that case, the statement is always false since n is always less than 5.

So, Us Really Smart C Programmers Who Have Been Burned By This Before
(hereafter, 'URSCPWHBBBTB') have long since taken to writing such things as:

    (5 <= X) && (X <= 9)

Anyways, that was C, so what about Python?

I decided to test if (a) Python could handle 'transitive' ways of writing
comparisons, and (b) if it emulated what most other languages do when you
explicity bracket the comparisons, and force sub-expression evaluation.

Here's a sample bit of code: It prints out the comparison, and the results


# test i<=j<=k behaviour, compare to (i<=j)<=k and i<=(j<=k)
for i in range(0,4):
 for j in range(0,4):
   for k in range(0,4):
     n = i <= j <= k # n = 1 if j between i and k
     x = ( i <= j) <= k # bug 1 ?
     y =  i <= (j <= k) # bug 2 ?
     print i,"<=",j,"<=",k," : ",n,"  ",x,y


Here's a Hack for the Mighty Pythonista to consider: Can you construct a
program that you can call like this:

    test_transitive( 0,100, '<=', 5 ) # generate a<=b<=c<=d<=e for range
0..100

Anyways, blessed be Guido, for near as I can figure it, he hath got it
right! :-)

Warren





More information about the Python-list mailing list