Python: check if one element is between two other elements

There are two elements: A and B. I don't know which element is larger. I want to check if the third element (C) is in between, 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?

+3


source to share


1 answer


Considering the two suggested methods, I personally find myself A < C < B or B < C < A

more readable than min(A,B) < C < max(A,B)

.

A very fast test also suggests that it is also faster on my computer (at least with small values int

). 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

      

+2


source







All Articles