I'm TAing an introductory course on Python this semester (using 3.4) and recently came across an exercise about operator precedence and using parentheses to make a statement evaluate to true.
The exact question is:
Add a single pair of parentheses to the expression so that it evaluates to true.
1 < -1 == 3 > 4
I assumed that the correct answer would be:
1 < -1 == (3 > 4)
Given that the comparison operators are all on the same level of precedence, they should evaluate from left to right, so it should evaluate as such:
1 < -1 == (3 > 4)
1 < -1 == False
False == False
True
But when I run the code it still returns false. I saw this question comparison operators' priority in Python vs C/C++ and the result of that expression makes sense to me; but in this case I've forced the evaluation of the latter statement before evaluating the rest of the expression, so I don't get why I'm still getting the wrong answer.
I've been staring at it for the past hour and I feel like I might be overlooking something obvious; if anyone could provide some insight as to what the correct solution might be it'd be greatly appreciated.
The task is provably impossible. Consider these three cases:
There is an open paren immediately before -1
.
There is an open paren between -
and 1
.
There is an open paren anywhere else.
These three cases represent every possible location for the parentheses.
In the first case, we have 1 < ( ... )
, where the ellipsis is a boolean expression. Since 1
is not less than either True
or False
, the entire expression is False
.
In the second case, we have 1 < -( ...)
, where the ellipsis is a boolean expression. Since 1
is not less than either -True
nor -False
, the entire expression is False
.
In the third case, we have 1 < -1 == ...
. Since all legs of a expression of chained operators must be True, and and since 1 < -1
is False, the entire expression is False
.
So, in every possible case, the result is False.