Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Check whether one element is between two other elements

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?

like image 594
jonie83 Avatar asked Apr 19 '26 22:04

jonie83


1 Answers

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
like image 144
Alex Riley Avatar answered Apr 22 '26 12:04

Alex Riley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!