There are two elements: A and B. I don't know which element is greater. I order to check whether a third element (C) is between them I do the following:
if A < C < B or B < C < A:
print("C is between A and B")
Is there a smarter / faster way to do this?
Looking at the two methods suggested so far, I personally think that A < C < B or B < C < A is more readable than min(A,B) < C < max(A,B).
A very quick test also suggests that it is also faster on my computer (at least with small int values). For example:
> python -m timeit("A, B, C = 74, 28, 19; A < C < B or B < C < A")
1000000 loops, best of 3: 0.267 usec per loop
> python -m timeit("A, B, C = 74, 28, 19; min(A, B) < C < max(A, B)")
1000000 loops, best of 3: 0.4 usec per loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With