Is if a[start] <= target < a[mid]
the same as a[start] <= target and target<a[mid] and a[start] < a[mid]
? (I think its not, but visually it looks like both are the same) How does this work under the hood? Searched on SO, but couldn't find an answer.
Asked
Active
Viewed 702 times
2
1 Answers
5
The
if a[start] <= target < a[mid]:
is essentially[*] the same as
if a[start] <= target and target < a[mid]:
(If true, it follows that a[start] < a[mid]
, since <=
should be transitive.)
[*] There is one subtlety that doesn't apply to your case but is worth knowing about. The chained form evaluates the middle expression just once, whereas the expanded form evaluates it twice. This could matter if the middle expression is costly to compute or has some side effects (such as printing something to the screen).
Relevant docs: https://docs.python.org/3/reference/expressions.html#comparisons
-
Ohh interesting! can you give me an example instance using just numbers where ```a[start] <= target and target < a[mid] ``` would evaluate to false – Sssssuppp Oct 12 '19 at 16:40
-
1@Satya you could use ternary operator like so: a = True if a[start] <= target < a[mid] else False. to get false, you can set a[start] to 1, target to 10, and a[mid] to 5. – mindless-overflow Oct 12 '19 at 16:49