【Python有坑系列】用is判断相等有坑

整数和字符串定义
python预先缓存了一个区间的整数用来减少内存的操作,但也正是如此,有时候会出很奇特的错误,例如:

>>> -8 is (-7 - 1)
False
>>> -3 is (-2 - 1)
True

另外一个例子

>>> (255 + 1) is (255 + 1)
True
>>> (256 + 1) is (256 + 1)
False

通过不断的测试,会发现(-3,256)这区间的整数都返回True,有的甚至是(-8,257)。默认情况下,[-5,256]会在解释器第一次启动时创建并缓存,所以才会有上面的奇怪的行为。这是个很常见但很容易被忽略的一个坑。解决方案是始终使用equality(==)运算符而不是 identity(is)运算符比较值。

Python还保留对常用字符串的引用,并且可以在比较is字符串的身份(即使用)时产生类似的混淆行为。

>>> 'python' is 'py' + 'thon'
True

python字符串被缓存了,所有python字符串都是该对象的引用,对于不常见的字符串,即使字符串相等,比较身份也会失败。

>>> 'this is not a common string' is 'this is not' + ' a common string'
False
>>> 'this is not a common string' == 'this is not' + ' a common string'
True

所以,就像整数规则一样,总是使用equal(==)运算符而不是 identity(is)运算符比较字符串值。
--------------------- 
作者:piapiada 
来源:CSDN 
原文:https://blog.csdn.net/piapiada/article/details/77473437 
版权声明:本文为博主原创文章,转载请附上博文链接!

发布了392 篇原创文章 · 获赞 487 · 访问量 239万+
展开阅读全文

核电站 Nuclear Plants

12-27

Description The Great Plain of Algorithmia plays an extremely important role in the agriculture of the Bandulu Kingdom: this is the only place where barley (Hordeum vulgare), an essential ingredient of beer, can be produced. Unfortunately, it is not possible to grow barley on the full area of the plain, as several nuclear plants have recently been built, and you cannot grow barley near a nuclear plant (since you do not want to produce giant-size, aggressive, man-eating barley-mutants). Your task is to write a program that determines the size of the area that can be used for growing barley. The Great Plain of Algorithmia is an n x m km2 rectangle, the coordinates of the four corners being (0, 0),(0, m),(n, 0) and (n, m) . There are two types of nuclear plants: small and large. You are not allowed to grow barley within 0.58km of a small nuclear plant or within 1.31km of a large nuclear plant. Input The input contains several blocks of test cases. Each block begins with a line containing four integers: 1 ≤ n, m ≤ 10000 describe the size of the plain, ks ≤ 100 is the number of small nuclear plants, and kl ≤ 100 is the number of large nuclear plants. The next ks lines describe the coordinates of the small nuclear plants, each line contains two integers 0 ≤ x ≤ n and 0 ≤ y ≤ m . The next kl lines describe the large nuclear plants in a similar fashion. The input is terminated by a block with n = m = ks = kl = 0 . Output For each test case, you have to output a single line containing the area that can be used for growing barley. This number should be a real value with two digits of precision. To avoid rounding problems, we accept solutions with a maximum of ±0.01 error. Sample Input 10 10 2 2 2 2 4 4 5 6 1 8 10 10 1 0 5 5 0 0 0 0 Sample Output 87.46 98.94 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览