Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

python - How does interval comparison work?

Somehow, this works:

def in_range(min, test, max):
    return min <= test <= max

print in_range(0, 5, 10)  # True
print in_range(0, 15, 10)  # False

However, I can't quite figure out the order of operations here. Let's test the False case:

print 0 <= 15 <= 10  # False
print (0 <= 15) <= 10  # True
print 0 <= (15 <= 10)  # True

Clearly, this isn't resolving to a simple order of operations issue. Is the interval comparison a special operator, or is something else going on?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unlike most languages, Python supports chained comparison operators and it evaluates them as they would be evaluated in normal mathematics.

This line:

return min <= test <= max

is evaluated by Python like this:

return (min <= test) and (test <= max)

Most other languages however would evaluate it like this:

return (min <= test) <= max

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...