简体   繁体   English

确定整数是否在另外两个整数之间

[英]Determine whether integer is between two other integers

How do I determine whether a given integer is between two other integers (eg greater than/equal to 10000 and less than/equal to 30000 )?如何确定给定整数是否介于其他两个整数之间(例如大于/等于10000和小于/等于30000 )?

What I've attempted so far is not working:到目前为止我所尝试的是行不通的:

if number >= 10000 and number >= 30000:
    print ("you have to pay 5% taxes")
if 10000 <= number <= 30000:
    pass

For details, see the docs .有关详细信息,请参阅文档

>>> r = range(1, 4)
>>> 1 in r
True
>>> 2 in r
True
>>> 3 in r
True
>>> 4 in r
False
>>> 5 in r
False
>>> 0 in r
False

Your operator is incorrect.您的运营商不正确。 Should be if number >= 10000 and number <= 30000: .应该是if number >= 10000 and number <= 30000: Additionally, Python has a shorthand for this sort of thing, if 10000 <= number <= 30000: .此外,Python 对这类事情有一个简写, if 10000 <= number <= 30000:

Your code snippet,你的代码片段,

if number >= 10000 and number >= 30000:
    print ("you have to pay 5% taxes")

actually checks if number is larger than both 10000 and 30000.实际上检查数字是否大于 10000 和 30000。

Assuming you want to check that the number is in the range 10000 - 30000, you could use the Python interval comparison:假设您要检查数字是否在 10000 - 30000 范围内,您可以使用 Python 间隔比较:

if 10000 <= number <= 30000:
    print ("you have to pay 5% taxes")

This Python feature is further described in the Python documentation . Python 文档 中进一步描述此 Python 功能。

There are two ways to compare three integers and check whether b is between a and c :两种方法可以比较三个整数并检查b是否在ac之间:

if a < b < c:
    pass

and

if a < b and b < c:
    pass

The first one looks like more readable, but the second one runs faster .第一个看起来更具可读性,但第二个运行得更快

Let's compare using dis.dis :让我们使用dis.dis进行比较:

>>> dis.dis('a < b and b < c')
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 COMPARE_OP               0 (<)
              6 JUMP_IF_FALSE_OR_POP    14
              8 LOAD_NAME                1 (b)
             10 LOAD_NAME                2 (c)
             12 COMPARE_OP               0 (<)
        >>   14 RETURN_VALUE
>>> dis.dis('a < b < c')
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 DUP_TOP
              6 ROT_THREE
              8 COMPARE_OP               0 (<)
             10 JUMP_IF_FALSE_OR_POP    18
             12 LOAD_NAME                2 (c)
             14 COMPARE_OP               0 (<)
             16 RETURN_VALUE
        >>   18 ROT_TWO
             20 POP_TOP
             22 RETURN_VALUE
>>>

and using timeit :并使用timeit

~$ python3 -m timeit "1 < 2 and 2 < 3"
10000000 loops, best of 3: 0.0366 usec per loop

~$ python3 -m timeit "1 < 2 < 3"
10000000 loops, best of 3: 0.0396 usec per loop

also, you may use range , as suggested before, however it is much more slower.此外,您可以使用range ,如前所述,但它要慢得多。

Define the range between the numbers:定义数字之间的范围:

r = range(1,10)

Then use it:然后使用它:

if num in r:
    print("All right!")
if number >= 10000 and number <= 30000:
    print ("you have to pay 5% taxes")

The trouble with comparisons is that they can be difficult to debug when you put a >= where there should be a <=比较的麻烦在于,当您将>=放在应该有<=位置时,它们可能难以调试

#                             v---------- should be <
if number >= 10000 and number >= 30000:
    print ("you have to pay 5% taxes")

Python lets you just write what you mean in words Python 让你只文字表达你的意思

if number in xrange(10000, 30001): # ok you have to remember 30000 + 1 here :)

In Python3, you need to use range instead of xrange .在 Python3 中,您需要使用range而不是xrange

edit: People seem to be more concerned with microbench marks and how cool chaining operations.编辑:人们似乎更关心微基准测试和链接操作有多酷。 My answer is about defensive (less attack surface for bugs) programming.我的答案是关于防御性(漏洞的攻击面较少)编程。

As a result of a claim in the comments, I've added the micro benchmark here for Python3.5.2由于评论中的声明,我在此处为 Python3.5.2 添加了微基准测试

$ python3.5 -m timeit "5 in range(10000, 30000)"
1000000 loops, best of 3: 0.266 usec per loop
$ python3.5 -m timeit "10000 <= 5 < 30000"
10000000 loops, best of 3: 0.0327 usec per loop

If you are worried about performance, you could compute the range once如果您担心性能,您可以计算一次范围

$ python3.5 -m timeit -s "R=range(10000, 30000)" "5 in R"
10000000 loops, best of 3: 0.0551 usec per loop

Suppose there are 3 non-negative integers: a , b , and c .假设有 3 个非负整数: abc Mathematically speaking, if we want to determine if c is between a and b , inclusively, one can use this formula:从数学上讲,如果我们要确定c是否介于ab之间,可以使用以下公式:

(c - a) * (b - c) >= 0 (c - a) * (b - c) >= 0

or in Python:或在 Python 中:

> print((c - a) * (b - c) >= 0)
True

I'm adding a solution that nobody mentioned yet, using Interval class from sympy library:我添加了一个尚未提及的解决方案,使用 sympy 库中的 Interval 类:

from sympy import Interval

lower_value, higher_value = 10000, 30000
number = 20000

 # to decide whether your interval shhould be open or closed use left_open and right_open 
interval = Interval(lower_value, higher_value, left_open=False, right_open=False)
if interval.contains(number):
    print("you have to pay 5% taxes")

You want the output to print the given statement if and only if the number falls between 10,000 and 30,000.当且仅当数字介于 10,000 和 30,000 之间时,您希望输出打印给定的语句。

Code should be;代码应该是;

if number >= 10000 and number <= 30000:
    print("you have to pay 5% taxes")

您使用了 >=30000,因此如果 number 为 45000,它将进入循环,但我们需要它大于 10000 但小于 30000。将其更改为 <=30000 即可!

While 10 <= number <= 20 works in Python, I find this notation using range() more readable:虽然10 <= number <= 20在 Python 中有效,但我发现使用range()这种表示法更具可读性:

if number in range(10, 21):
    print("number is between 10 (inclusive) and 21 (exclusive)")
else:
    print("outside of range!")

Keep in mind that the 2nd, upper bound parameter is not included in the range set as can be verified with:请记住,第二个上限参数不包含在范围集中,可以通过以下方式进行验证:

>>> list(range(10, 21))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

Below are few possible ways, ordered from best to worse performance (ie first one will perform best)以下是几种可能的方法,按性能从好到坏排序(即第一个性能最好)

 if 10000 <= b and b <=30000:
    print ("you have to pay 5% taxes")

 if 10000 <= number <= 30000:
    print ("you have to pay 5% taxes")

 if number in range(10000,30001):
    print ("you have to pay 5% taxes")

How do I determine whether a given integer is between two other integers (eg greater than/equal to 10000 and less than/equal to 30000 )?如何确定给定的整数是否介于两个其他整数之间(例如,大于/等于10000且小于/等于30000 )?

I'm using 2.3 IDLE and what I've attempted so far is not working:我正在使用 2.3 IDLE 并且到目前为止我尝试过的不起作用:

if number >= 10000 and number >= 30000:
    print ("you have to pay 5% taxes")

Try this simple function;试试这个简单的功能; it checks if A is between B and C ( B and C may not be in the right order):它检查A是否在BC之间( BC的顺序可能不正确):

def isBetween(A, B, C):
    Mi = min(B, C)
    Ma = max(B, C)
    return Mi <= A <= Ma

so isBetween(2, 10, -1) is the same as isBetween(2, -1, 10) .所以isBetween(2, 10, -1)isBetween(2, -1, 10)

The condition should be,条件应该是,

if number == 10000 and number <= 30000:
     print("5% tax payable")

reason for using number == 10000 is that if number's value is 50000 and if we use number >= 10000 the condition will pass, which is not what you want.使用number == 10000原因是如果 number 的值为 50000 并且如果我们使用number >= 10000条件将通过,这不是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM