Python: Check whether one element is between two other elements

时间:2022-12-02 14:09:37

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:

有两个元素:A和B.我不知道哪个元素更大。我要检查第三个元素(C)是否在它们之间我做了以下事情:

if A < C < B or B < C < A:
    print("C is between A and B")

Is there a smarter / faster way to do this?

有更聪明/更快的方法吗?

1 个解决方案

#1


2  

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

A very quick test also suggests that it is also faster on my computer (at least with small int values). For example:

一个非常快速的测试也表明它在我的计算机上也更快(至少有小的int值)。例如:

> 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

#1


2  

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

A very quick test also suggests that it is also faster on my computer (at least with small int values). For example:

一个非常快速的测试也表明它在我的计算机上也更快(至少有小的int值)。例如:

> 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