An operator riddle-Collection of common programming errors

  • Because Python uses a slightly interpretation of your input:

    Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.

    This means your lines will be interpreted as

    a < a < a = a < a and a < a // returns false
    c < b < a = c < b and b < a // returns false
    c > b > a = c > b and b > a // returns true
    a < c > b = a < c and c > b // returns true
    

    In C-style languages, an comparison expression will evaluate to either false (integer value 0) or true (integer value 1). So in C it will behave like

    a < a < a = (a < a) < a = 0 < a  // returns true
    c < b < a = (c < b) < a = 0 < a  // returns true
    c > b > a = (c > b) > a = 1 > a // returns false
    a < c > b = (a < c) > b = 0 > b // returns false
    

    Note that almost all languages define operators with a boolean return value, but since boolean values can be implicit converted to zero or one the proposition above is still valid:

    // C++ example
    struct myComparableObject{
        int data;
        bool operator

Originally posted 2013-11-10 00:09:00.